Imports System
Imports System.IO
Imports Ionic.Zip
Imports System.Xml

Public Class Form1
    Dim projectchanged As Boolean
    Dim tempdirectory As String
    Dim ebookdirectory As String
    Dim opfdirectory As String
    Dim coverimagefile As String
    Dim relativecoverimagefile As String
    Dim coverfile As String
    Dim opffile As String
    Dim tocfile As String
    Dim pagemapfile As String
    Dim searchResults As String()
    Dim m_MouseIsDown As Boolean
    Public Sub DeleteDirContents(ByVal dir As IO.DirectoryInfo)
        Dim fa() As IO.FileInfo
        Dim f As IO.FileInfo

        fa = dir.GetFiles

        For Each f In fa
            f.Delete()
        Next

        Dim da() As IO.DirectoryInfo
        Dim d1 As IO.DirectoryInfo

        da = dir.GetDirectories
        For Each d1 In da
            DeleteDirContents(d1)
        Next
    End Sub
    Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If projectchanged Then
            DialogResult = Dialog1.ShowDialog
            If DialogResult = Windows.Forms.DialogResult.Cancel Then
                Exit Sub
            End If
            If DialogResult = Windows.Forms.DialogResult.Yes Then
                SaveEpub()
            End If
        End If

        'File chooser
        OpenFileDialog1.Filter = "EPub Files (*.epub)|*.epub|All files (*.*)|*.*"
        OpenFileDialog1.FilterIndex = 1
        OpenFileDialog1.FileName = ""
        If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            TextBox1.Text = ""
            TextBox2.Text = ""
            TextBox3.Text = ""
            TextBox4.Text = ""
            TextBox5.Text = ""
            TextBox6.Text = ""
            TextBox7.Text = ""
            TextBox8.Text = ""
            TextBox9.Text = ""
            TextBox10.Text = ""
            TextBox11.Text = ""
            TextBox12.Text = ""
            TextBox13.Text = ""
            TextBox14.Text = ""
            TextBox15.Text = ""
            TextBox16.Text = ""
            ComboBox1.SelectedIndex = -1
            ComboBox2.SelectedIndex = -1
            PictureBox1.Image = Nothing
            Label4.Visible = False
            Button1.Visible = False
            OpenEPub()
        End If
    End Sub

    Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim metadatafile, optionaltext As String
        Dim startpos, endpos, lenheader As Integer

        'Rewrite .opf file (just the metadata section)
        RichTextBox1.LoadFile(opffile, RichTextBoxStreamType.PlainText)
        metadatafile = RichTextBox1.Text

        'Output title
        startpos = InStr(metadatafile, "<dc:title")
        If startpos <> 0 Then
            endpos = InStr(metadatafile, "</dc:title>")
            lenheader = Len("<dc:title")
            metadatafile = Mid(metadatafile, 1, startpos + lenheader - 1) + ">" + TextBox1.Text + Mid(metadatafile, endpos)
            RichTextBox1.Text = metadatafile
        End If

        'Output first creator
        startpos = InStr(metadatafile, "<dc:creator")
        If startpos <> 0 Then
            endpos = InStr(metadatafile, "</dc:creator>")
            lenheader = Len("<dc:creator")

            'If optional attributes
            If TextBox12.Text <> "" Then
                optionaltext = ""
                If ((ComboBox1.SelectedIndex = 0) Or (ComboBox1.SelectedIndex = -1)) Then optionaltext = " opf:role=" + Chr(34) + "aut" + Chr(34)
                If ComboBox1.SelectedIndex = 1 Then optionaltext = " opf:role=" + Chr(34) + "edt" + Chr(34)
                If ComboBox1.SelectedIndex = 2 Then optionaltext = " opf:role=" + Chr(34) + "ill" + Chr(34)
                If ComboBox1.SelectedIndex = 3 Then optionaltext = " opf:role=" + Chr(34) + "trl" + Chr(34)
                optionaltext = optionaltext + " opf:file-as=" + Chr(34) + TextBox12.Text + Chr(34) + ">"
            Else
                optionaltext = ">"
            End If
            metadatafile = Mid(metadatafile, 1, startpos + lenheader - 1) + optionaltext + TextBox2.Text + Mid(metadatafile, endpos)

            'Output second creator?
            If TextBox3.Text <> "" Then
                endpos = InStr(metadatafile, "</dc:creator>") 'find end of first creator
                startpos = InStr(endpos, metadatafile, "<dc:creator") 'look for another one
                'Get optional attributes
                If TextBox13.Text <> "" Then
                    optionaltext = ""
                    If ((ComboBox2.SelectedIndex = 0) Or (ComboBox2.SelectedIndex = -1)) Then optionaltext = " opf:role=" + Chr(34) + "aut" + Chr(34)
                    If ComboBox2.SelectedIndex = 1 Then optionaltext = " opf:role=" + Chr(34) + "edt" + Chr(34)
                    If ComboBox2.SelectedIndex = 2 Then optionaltext = " opf:role=" + Chr(34) + "ill" + Chr(34)
                    If ComboBox2.SelectedIndex = 3 Then optionaltext = " opf:role=" + Chr(34) + "trl" + Chr(34)
                    optionaltext = optionaltext + " opf:file-as=" + Chr(34) + TextBox13.Text + Chr(34) + ">"
                Else
                    optionaltext = ">"
                End If
                If startpos <> 0 Then
                    endpos = InStr(startpos, metadatafile, "</dc:creator>")
                    lenheader = Len("<dc:creator")
                    metadatafile = Mid(metadatafile, 1, startpos + lenheader - 1) + optionaltext + TextBox3.Text + Mid(metadatafile, endpos)
                Else
                    'Original file did not have second creator
                    metadatafile = Mid(metadatafile, 1, endpos + 13) + Chr(13) + Chr(10) + Chr(9) + "<dc:creator" + optionaltext + TextBox3.Text + "</dc:creator>" + Chr(13) + Chr(10) + Mid(metadatafile, endpos + 14)
                End If
            End If
        End If

        'Output description
        If TextBox4.Text <> "" Then
            startpos = InStr(metadatafile, "<dc:description>")
            If startpos <> 0 Then
                endpos = InStr(metadatafile, "</dc:description>")
                lenheader = Len("<dc:description>")
                metadatafile = Mid(metadatafile, 1, startpos + lenheader - 1) + TextBox4.Text + Mid(metadatafile, endpos)
            Else
                endpos = InStr(metadatafile, "</dc:title>")
                metadatafile = Mid(metadatafile, 1, endpos + 11) + Chr(13) + Chr(10) + Chr(9) + "<dc:description>" + TextBox4.Text + "</dc:description>" + Chr(13) + Chr(10) + Mid(metadatafile, endpos + 12)
            End If
        End If

        'Output publisher
        If TextBox5.Text <> "" Then
            startpos = InStr(metadatafile, "<dc:publisher>")
            If startpos <> 0 Then
                endpos = InStr(metadatafile, "</dc:publisher>")
                lenheader = Len("<dc:publisher>")
                metadatafile = Mid(metadatafile, 1, startpos + lenheader - 1) + TextBox5.Text + Mid(metadatafile, endpos)
            Else
                endpos = InStr(metadatafile, "</dc:title>")
                metadatafile = Mid(metadatafile, 1, endpos + 11) + Chr(13) + Chr(10) + Chr(9) + "<dc:publisher>" + TextBox5.Text + "</dc:publisher>" + Chr(13) + Chr(10) + Mid(metadatafile, endpos + 12)
            End If
        End If

        'Output date
        If TextBox6.Text <> "" Then
            startpos = InStr(metadatafile, "<dc:date")
            If startpos <> 0 Then
                endpos = InStr(metadatafile, "</dc:date>")
                lenheader = Len("<dc:date")
                metadatafile = Mid(metadatafile, 1, startpos + lenheader - 1) + " opf:event=" + Chr(34) + "original-publication" + Chr(34) + ">" + TextBox6.Text + Mid(metadatafile, endpos)
            Else
                endpos = InStr(metadatafile, "</dc:title>")
                metadatafile = Mid(metadatafile, 1, endpos + 11) + Chr(13) + Chr(10) + Chr(9) + "<dc:date" + " opf:event=" + Chr(34) + "original-publication" + Chr(34) + ">" + TextBox6.Text + "</dc:date>" + Chr(13) + Chr(10) + Mid(metadatafile, endpos + 12)
            End If
        End If

        'Output type
        If TextBox7.Text <> "" Then
            startpos = InStr(metadatafile, "<dc:type>")
            If startpos <> 0 Then
                endpos = InStr(metadatafile, "</dc:type>")
                lenheader = Len("<dc:type>")
                metadatafile = Mid(metadatafile, 1, startpos + lenheader - 1) + TextBox7.Text + Mid(metadatafile, endpos)
            Else
                endpos = InStr(metadatafile, "</dc:title>")
                metadatafile = Mid(metadatafile, 1, endpos + 11) + Chr(13) + Chr(10) + Chr(9) + "<dc:type>" + TextBox7.Text + "</dc:type>" + Chr(13) + Chr(10) + Mid(metadatafile, endpos + 12)
            End If
        End If

        'Output format
        If TextBox8.Text <> "" Then
            startpos = InStr(metadatafile, "<dc:format>")
            If startpos <> 0 Then
                endpos = InStr(metadatafile, "</dc:format>")
                lenheader = Len("<dc:format>")
                metadatafile = Mid(metadatafile, 1, startpos + lenheader - 1) + TextBox8.Text + Mid(metadatafile, endpos)
            Else
                endpos = InStr(metadatafile, "</dc:title>")
                metadatafile = Mid(metadatafile, 1, endpos + 11) + Chr(13) + Chr(10) + Chr(9) + "<dc:format>" + TextBox8.Text + "</dc:format>" + Chr(13) + Chr(10) + Mid(metadatafile, endpos + 12)
            End If
        End If

        'Output identifier
        If TextBox9.Text <> "" Then
            startpos = InStr(metadatafile, "<dc:identifier>")
            If startpos <> 0 Then
                endpos = InStr(metadatafile, "</dc:identifier>")
                lenheader = Len("<dc:identifier>")
                metadatafile = Mid(metadatafile, 1, startpos + lenheader - 1) + TextBox9.Text + Mid(metadatafile, endpos)
            Else
                endpos = InStr(metadatafile, "</dc:title>")
                metadatafile = Mid(metadatafile, 1, endpos + 11) + Chr(13) + Chr(10) + Chr(9) + "<dc:identifier>" + TextBox9.Text + "</dc:identifier>" + Chr(13) + Chr(10) + Mid(metadatafile, endpos + 12)
            End If
        End If

        'Output source
        If TextBox10.Text <> "" Then
            startpos = InStr(metadatafile, "<dc:source>")
            If startpos <> 0 Then
                endpos = InStr(metadatafile, "</dc:source>")
                lenheader = Len("<dc:source>")
                metadatafile = Mid(metadatafile, 1, startpos + lenheader - 1) + TextBox10.Text + Mid(metadatafile, endpos)
            Else
                endpos = InStr(metadatafile, "</dc:title>")
                metadatafile = Mid(metadatafile, 1, endpos + 11) + Chr(13) + Chr(10) + Chr(9) + "<dc:source>" + TextBox10.Text + "</dc:source>" + Chr(13) + Chr(10) + Mid(metadatafile, endpos + 12)
            End If
        End If

        'Output language
        If TextBox11.Text <> "" Then
            startpos = InStr(metadatafile, "<dc:language>")
            If startpos <> 0 Then
                endpos = InStr(metadatafile, "</dc:language>")
                lenheader = Len("<dc:language>")
                metadatafile = Mid(metadatafile, 1, startpos + lenheader - 1) + TextBox11.Text + Mid(metadatafile, endpos)
            Else
                endpos = InStr(metadatafile, "</dc:title>")
                metadatafile = Mid(metadatafile, 1, endpos + 11) + Chr(13) + Chr(10) + Chr(9) + "<dc:language>" + TextBox11.Text + "</dc:language>" + Chr(13) + Chr(10) + Mid(metadatafile, endpos + 12)
            End If
        End If

        RichTextBox1.Text = metadatafile
        RichTextBox1.SaveFile(opffile, RichTextBoxStreamType.PlainText)

        'Zip temp directory (after deleting original file)
        Dim fi As New FileInfo(OpenFileDialog1.FileName)
        fi.Delete()

        Using zip As ZipFile = New ZipFile
            zip.AddDirectory(ebookdirectory)
            zip.Save(OpenFileDialog1.FileName)
        End Using

        'Update interface
        Me.Text = IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
        Button3.Enabled = False
        projectchanged = False
    End Sub

    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
        projectchanged = True
        Button3.Enabled = True
        Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
    End Sub

    Private Sub ComboBox2_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox2.SelectedIndexChanged
        projectchanged = True
        Button3.Enabled = True
        Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
    End Sub

    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        projectchanged = True
        Button3.Enabled = True
        Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
    End Sub

    Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
        projectchanged = True
        Button3.Enabled = True
        Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
    End Sub

    Private Sub TextBox3_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox3.TextChanged
        projectchanged = True
        Button3.Enabled = True
        Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
    End Sub

    Private Sub TextBox4_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox4.TextChanged
        projectchanged = True
        Button3.Enabled = True
        Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
    End Sub

    Private Sub TextBox5_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox5.TextChanged
        projectchanged = True
        Button3.Enabled = True
        Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
    End Sub

    Private Sub TextBox6_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox6.TextChanged
        projectchanged = True
        Button3.Enabled = True
        Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
    End Sub

    Private Sub TextBox7_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox7.TextChanged
        projectchanged = True
        Button3.Enabled = True
        Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
    End Sub

    Private Sub TextBox8_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox8.TextChanged
        projectchanged = True
        Button3.Enabled = True
        Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
    End Sub

    Private Sub TextBox9_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox9.TextChanged
        projectchanged = True
        Button3.Enabled = True
        Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
    End Sub

    Private Sub TextBox10_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox10.TextChanged
        projectchanged = True
        Button3.Enabled = True
        Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
    End Sub

    Private Sub TextBox11_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox11.TextChanged
        projectchanged = True
        Button3.Enabled = True
        Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
    End Sub

    Private Sub TextBox12_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox12.TextChanged
        projectchanged = True
        Button3.Enabled = True
        Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"

        If ComboBox1.SelectedIndex = -1 Then ComboBox1.SelectedIndex = 0
    End Sub

    Private Sub TextBox13_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox13.TextChanged
        projectchanged = True
        Button3.Enabled = True
        Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"

        If ComboBox2.SelectedIndex = -1 Then ComboBox2.SelectedIndex = 0
    End Sub

    Private Sub TextBox14_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox14.TextChanged
        projectchanged = True
        Button3.Enabled = True
        Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
    End Sub

    Private Sub TextBox15_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox15.TextChanged
        projectchanged = True
        Button3.Enabled = True
        Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
    End Sub

    Private Sub TextBox16_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox16.TextChanged
        projectchanged = True
        Button3.Enabled = True
        Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If projectchanged Then
            DialogResult = Dialog1.ShowDialog()
            If DialogResult = Windows.Forms.DialogResult.No Then
                ChDir(tempdirectory)
                If (My.Computer.FileSystem.DirectoryExists(ebookdirectory)) Then
                    My.Computer.FileSystem.DeleteDirectory(ebookdirectory, FileIO.DeleteDirectoryOption.DeleteAllContents)
                End If
                End
            ElseIf DialogResult = Windows.Forms.DialogResult.Yes Then
                SaveEpub()
            End If
        Else
            ChDir(tempdirectory)
            If (My.Computer.FileSystem.DirectoryExists(ebookdirectory)) Then
                My.Computer.FileSystem.DeleteDirectory(ebookdirectory, FileIO.DeleteDirectoryOption.DeleteAllContents)
            End If
            End
        End If
    End Sub

    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If projectchanged Then
            DialogResult = Dialog1.ShowDialog()
            If DialogResult = Windows.Forms.DialogResult.No Then
                ChDir(tempdirectory)
                If (My.Computer.FileSystem.DirectoryExists(ebookdirectory)) Then
                    My.Computer.FileSystem.DeleteDirectory(ebookdirectory, FileIO.DeleteDirectoryOption.DeleteAllContents)
                End If
                End
            ElseIf DialogResult = Windows.Forms.DialogResult.Yes Then
                SaveEpub()
            Else
                e.Cancel = True
            End If
        Else
            ChDir(tempdirectory)
            If (My.Computer.FileSystem.DirectoryExists(ebookdirectory)) Then
                My.Computer.FileSystem.DeleteDirectory(ebookdirectory, FileIO.DeleteDirectoryOption.DeleteAllContents)
            End If
            End
        End If
    End Sub

    Private Sub OpenEPub()
        Dim metadatafile As String
        Dim instance As Integer

        'Unzip epub to temp directory
        tempdirectory = System.IO.Path.GetTempPath
        instance = 1
        ebookdirectory = tempdirectory + "EPUB" + Trim(Str(instance))
        While (My.Computer.FileSystem.DirectoryExists(ebookdirectory))
            instance = instance + 1
            ebookdirectory = tempdirectory + "EPUB" + Trim(Str(instance))
        End While
        MkDir(ebookdirectory)
        ChDir(ebookdirectory)

        Try
            Using zip As ZipFile = ZipFile.Read(OpenFileDialog1.FileName)
                Dim item As ZipEntry
                For Each item In zip
                    item.Extract()
                Next
            End Using
        Catch ex1 As Exception
            Console.Error.WriteLine("exception: {0}", ex1.ToString)
        End Try

        'Search for .opf file
        searchResults = Directory.GetFiles(ebookdirectory, "*.opf", SearchOption.AllDirectories)

        'Open .opf file into RichTextBox
        If searchResults.Length < 1 Then
            DialogResult = MsgBox("Error: Metadata not found." + Chr(10) + "This ebook is malformed.", MsgBoxStyle.OkOnly, "EPub Metadata Editor")
            Button19.Enabled = False
            opffile = ""
            Return
        Else
            opffile = searchResults(0)
            opfdirectory = Path.GetDirectoryName(opffile)
            RichTextBox1.LoadFile(opffile, RichTextBoxStreamType.PlainText)
            Button19.Enabled = True
        End If

        'Search for toc.ncx file
        searchResults = Directory.GetFiles(ebookdirectory, "*.ncx", SearchOption.AllDirectories)
        If searchResults.Length < 1 Then
            DialogResult = MsgBox("Error: Table of Contents file not found." + Chr(10) + "This ebook is malformed.", MsgBoxStyle.OkOnly, "EPub Metadata Editor")
            Button20.Enabled = False
            Button23.Enabled = False
            tocfile = ""
        Else
            tocfile = searchResults(0)
            Button20.Enabled = True
            Button23.Enabled = True
        End If

        'Search for page-map.xml file
        searchResults = Directory.GetFiles(ebookdirectory, "page-map.xml", SearchOption.AllDirectories)
        If searchResults.Length < 1 Then
            Button24.Enabled = False
            pagemapfile = ""
        Else
            pagemapfile = searchResults(0)
            Button24.Enabled = True
        End If

        'Extract metadata into textboxes
        metadatafile = RichTextBox1.Text
        ExtractMetadata(metadatafile)

        'Update interface
        Me.Text = IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
        projectchanged = False
        TextBox1.Enabled = True
        TextBox2.Enabled = True
        TextBox3.Enabled = True
        TextBox4.Enabled = True
        TextBox5.Enabled = True
        TextBox6.Enabled = True
        TextBox7.Enabled = True
        TextBox8.Enabled = True
        TextBox9.Enabled = True
        TextBox10.Enabled = True
        TextBox11.Enabled = True
        TextBox12.Enabled = True
        TextBox13.Enabled = True
        TextBox14.Enabled = True
        TextBox15.Enabled = True
        TextBox16.Enabled = True
        ComboBox1.Enabled = True
        ComboBox2.Enabled = True
        PictureBox1.Enabled = True
        Button5.Enabled = True
        Button6.Enabled = True
        Button7.Enabled = True
        Button13.Enabled = True
        Button14.Enabled = True
        Button15.Enabled = True
        Button18.Enabled = True
        Button21.Enabled = True
        Button22.Enabled = True
        Button25.Enabled = True
        SaveImageAsToolStripMenuItem.Enabled = True
    End Sub
    Private Sub ExtractMetadata(ByVal metadatafile As String)
        Dim startpos, endpos, lenheader, fileaspos, temploop, rolepos, coverfilepos, nextcharpos As Integer
        Dim rolestring, coverfiletext, langtext, hreftype, nextchar, tempstring As String

        'Get title
        startpos = InStr(metadatafile, "<dc:title")
        If startpos <> 0 Then
            endpos = InStr(metadatafile, "</dc:title>")
            lenheader = Len("<dc:title")
            If Mid(metadatafile, startpos + lenheader, 1) = ">" Then
                TextBox1.Text = Mid(metadatafile, startpos + lenheader + 1, endpos - startpos - lenheader - 1)
            Else
                'get optional attributes
                fileaspos = InStr(startpos, metadatafile, "opf:file-as=")
                If fileaspos <> 0 Then
                    For temploop = fileaspos + 13 To endpos
                        If Mid(metadatafile, temploop, 1) = Chr(34) Then
                            TextBox16.Text = Mid(metadatafile, fileaspos + 13, temploop - fileaspos - 13)
                        End If
                    Next
                End If
                For temploop = startpos To endpos
                    If Mid(metadatafile, temploop, 1) = ">" Then
                        TextBox1.Text = Mid(metadatafile, temploop + 1, endpos - temploop - 1)
                    End If
                Next
            End If
        End If

        'Get creator
        startpos = InStr(metadatafile, "<dc:creator")
        If startpos <> 0 Then
            endpos = InStr(metadatafile, "</dc:creator>")
            lenheader = Len("<dc:creator")
            If Mid(metadatafile, startpos + lenheader + 1) = ">" Then
                TextBox2.Text = Mid(metadatafile, startpos + lenheader, endpos - startpos - lenheader)
            Else
                'Get optional attributes
                fileaspos = InStr(startpos, metadatafile, "opf:file-as=")
                If fileaspos <> 0 Then
                    For temploop = fileaspos + 13 To endpos
                        If Mid(metadatafile, temploop, 1) = Chr(34) Then
                            TextBox12.Text = Mid(metadatafile, fileaspos + 13, temploop - fileaspos - 13)
                            GoTo findrole1
                        End If
                    Next
                End If
findrole1:
                rolepos = InStr(startpos, metadatafile, "opf:role=")
                If rolepos <> 0 Then
                    rolestring = Mid(metadatafile, rolepos + 10, 3)
                    If rolestring = "aut" Then
                        ComboBox1.SelectedIndex = 0
                    ElseIf rolestring = "edt" Then
                        ComboBox1.SelectedIndex = 1
                    ElseIf rolestring = "ill" Then
                        ComboBox1.SelectedIndex = 2
                    ElseIf rolestring = "trl" Then
                        ComboBox1.SelectedIndex = 3
                    Else
                        ComboBox1.SelectedIndex = 0
                    End If
                Else
                    ComboBox1.SelectedIndex = 0
                End If

                For temploop = startpos To endpos
                    If Mid(metadatafile, temploop, 1) = ">" Then
                        TextBox2.Text = Mid(metadatafile, temploop + 1, endpos - temploop - 1)
                    End If
                Next
            End If
        End If

        If endpos = 0 Then GoTo skipsecondcreator

        'Look for second creator
        startpos = InStr(endpos, metadatafile, "<dc:creator")
        If startpos <> 0 Then
            endpos = InStr(startpos, metadatafile, "</dc:creator>")
            lenheader = Len("<dc:creator")
            If Mid(metadatafile, startpos + 1) = ">" Then
                TextBox3.Text = Mid(metadatafile, startpos + lenheader, endpos - startpos - lenheader)
            Else
                'Get optional attributes
                fileaspos = InStr(startpos, metadatafile, "opf:file-as=")
                If fileaspos <> 0 Then
                    For temploop = fileaspos + 13 To endpos
                        If Mid(metadatafile, temploop, 1) = Chr(34) Then
                            TextBox13.Text = Mid(metadatafile, fileaspos + 13, temploop - fileaspos - 13)
                            GoTo findrole2
                        End If
                    Next
                End If
findrole2:
                rolepos = InStr(startpos, metadatafile, "opf:role=")
                If rolepos <> 0 Then
                    rolestring = Mid(metadatafile, rolepos + 10, 3)
                    If rolestring = "aut" Then ComboBox2.SelectedIndex = 0
                    If rolestring = "edt" Then ComboBox2.SelectedIndex = 1
                    If rolestring = "ill" Then ComboBox2.SelectedIndex = 2
                    If rolestring = "trl" Then ComboBox2.SelectedIndex = 3
                End If

                For temploop = startpos To endpos
                    If Mid(metadatafile, temploop, 1) = ">" Then
                        TextBox3.Text = Mid(metadatafile, temploop + 1, endpos - temploop - 1)
                    End If
                Next
            End If
        End If

skipsecondcreator:

        'Get (Calibre) Series and Series Index
        startpos = InStr(metadatafile, "<meta name=" & Chr(34) & "calibre:series" & Chr(34))
        If startpos <> 0 Then
            startpos = InStr(startpos, metadatafile, "content=" & Chr(34))
            If startpos <> 0 Then
                endpos = InStr(startpos, metadatafile, "/>")
                lenheader = Len("content=" & Chr(34))
                TextBox15.Text = Mid(metadatafile, startpos + lenheader, endpos - startpos - lenheader - 1)
            End If

            startpos = InStr(metadatafile, "<meta name=" & Chr(34) & "calibre:series_index" & Chr(34))
            If startpos <> 0 Then
                startpos = InStr(startpos, metadatafile, "content=" & Chr(34))
                If startpos <> 0 Then
                    endpos = InStr(startpos, metadatafile, "/>")
                    lenheader = Len("content=" & Chr(34))
                    TextBox14.Text = Mid(metadatafile, startpos + lenheader, endpos - startpos - lenheader - 1)
                End If

            End If
        End If

        'Get Description
        startpos = InStr(metadatafile, "<dc:description>")
        If startpos <> 0 Then
            endpos = InStr(metadatafile, "</dc:description>")
            lenheader = Len("<dc:description>")
            TextBox4.Text = Mid(metadatafile, startpos + lenheader, endpos - startpos - lenheader)
        End If

        'Get Publisher
        startpos = InStr(metadatafile, "<dc:publisher>")
        If startpos <> 0 Then
            endpos = InStr(metadatafile, "</dc:publisher>")
            lenheader = Len("<dc:publisher>")
            TextBox5.Text = Mid(metadatafile, startpos + lenheader, endpos - startpos - lenheader)
        End If

        'Get Date
        startpos = InStr(metadatafile, "<dc:date")
        If startpos <> 0 Then
            endpos = InStr(metadatafile, "</dc:date>")
            lenheader = Len("<dc:date")
            If Mid(metadatafile, startpos + 1) = ">" Then
                TextBox6.Text = Mid(metadatafile, startpos + lenheader, endpos - startpos - lenheader)
            Else
                'Get optional attributes
                fileaspos = InStr(metadatafile, "opf:event=" + Chr(34) + "original-publication")
                If fileaspos <> 0 Then
                    TextBox6.Text = Mid(metadatafile, fileaspos + 33, endpos - fileaspos - 33)
                End If
            End If
        End If

        'Get Type
        startpos = InStr(metadatafile, "<dc:type>")
        If startpos <> 0 Then
            endpos = InStr(metadatafile, "</dc:type>")
            lenheader = Len("<dc:type>")
            TextBox7.Text = Mid(metadatafile, startpos + lenheader, endpos - startpos - lenheader)
        End If

        'Get Format
        startpos = InStr(metadatafile, "<dc:format>")
        If startpos <> 0 Then
            endpos = InStr(metadatafile, "</dc:format>")
            lenheader = Len("<dc:format>")
            TextBox8.Text = Mid(metadatafile, startpos + lenheader, endpos - startpos - lenheader)
        End If

        'Get Identifier
        startpos = InStr(metadatafile, "<dc:identifier>")
        If startpos <> 0 Then
            endpos = InStr(metadatafile, "</dc:identifier>")
            lenheader = Len("<dc:identifier>")
            TextBox9.Text = Mid(metadatafile, startpos + lenheader, endpos - startpos - lenheader)
        End If

        'Get Source
        startpos = InStr(metadatafile, "<dc:source>")
        If startpos <> 0 Then
            endpos = InStr(metadatafile, "</dc:source>")
            lenheader = Len("<dc:source>")
            TextBox10.Text = Mid(metadatafile, startpos + lenheader, endpos - startpos - lenheader)
        End If

        'Get Language
        startpos = InStr(metadatafile, "<dc:language>")
        If startpos <> 0 Then
            endpos = InStr(metadatafile, "</dc:language>")
            lenheader = Len("<dc:language>")
            langtext = Mid(metadatafile, startpos + lenheader, endpos - startpos - lenheader)
            TextBox11.Text = langtext
        End If

        'Get Cover
        startpos = InStr(metadatafile, "<guide")
        If startpos = 0 Then
            startpos = InStr(metadatafile, "<opf:guide")
        End If
        If startpos = 0 Then
            'Some Sony Reader Library files have no <guide>
            startpos = InStr(metadatafile, "<manifest")
            If startpos = 0 Then
                startpos = InStr(metadatafile, "<opf:manifest")
            End If
            If startpos <> 0 Then
                hreftype = "id=" + Chr(34) + "cov" + Chr(34)
                coverfilepos = InStr(startpos, metadatafile, hreftype)
                If coverfilepos = 0 Then
                    hreftype = "id=" + Chr(34) + "cover" + Chr(34)
                    coverfilepos = InStr(startpos, metadatafile, hreftype)
                    If coverfilepos = 0 Then
                        hreftype = "id=" + Chr(34) + "coverpage" + Chr(34)
                        coverfilepos = InStr(startpos, metadatafile, hreftype)
                    End If
                End If
            End If
        Else
            hreftype = "type=" + Chr(34) + "cover" + Chr(34)
            coverfilepos = InStr(startpos, metadatafile, hreftype)
            If coverfilepos = 0 Then
                'some Sony Reader Library files require different processing
                hreftype = "title=" + Chr(34) + "Cover" + Chr(34)
                coverfilepos = InStr(startpos, metadatafile, hreftype)
                If coverfilepos = 0 Then
                    hreftype = "title=" + Chr(34) + "Cover Page" + Chr(34)
                    coverfilepos = InStr(startpos, metadatafile, hreftype)
                    If coverfilepos = 0 Then
                        hreftype = "type=" + Chr(34) + "coverimagestandard" + Chr(34)
                        coverfilepos = InStr(startpos, metadatafile, hreftype)
                    End If
                End If
            End If
        End If

        If coverfilepos = 0 Then GoTo didnotfindhref

        'find href (scanning forwards) 
        nextcharpos = coverfilepos + 1
        nextchar = Mid(metadatafile, nextcharpos, 1)
        While nextchar <> ">"
            tempstring = Mid(metadatafile, nextcharpos, 5)
            If tempstring = "href=" Then GoTo foundhref
            nextcharpos = nextcharpos + 1
            nextchar = Mid(metadatafile, nextcharpos, 1)
        End While

        'find href (scanning backwards) 
        nextcharpos = coverfilepos - 1
        nextchar = Mid(metadatafile, nextcharpos, 1)
        While nextchar <> "<"
            tempstring = Mid(metadatafile, nextcharpos, 5)
            If tempstring = "href=" Then GoTo foundhref
            nextcharpos = nextcharpos - 1
            nextchar = Mid(metadatafile, nextcharpos, 1)
        End While
        GoTo didnotfindhref
foundhref:
        coverfilepos = nextcharpos
        endpos = InStr(coverfilepos + 6, metadatafile, Chr(34))
        coverfile = Path.GetDirectoryName(opffile) + "\" + Replace(Mid(metadatafile, coverfilepos + 6, endpos - coverfilepos - 6), "/", "\")

        If Path.GetExtension(coverfile) = ".jpg" Then
            If System.IO.File.Exists(coverfile) Then
                coverimagefile = coverfile
                PictureBox1.ImageLocation = coverfile
                PictureBox1.Load()
                ChangeImageToolStripMenuItem.Enabled = True
                AddImageToolStripMenuItem.Enabled = False
                GoTo updateinterface
            End If
        ElseIf Path.GetExtension(coverfile) = ".png" Then
            If System.IO.File.Exists(coverfile) Then
                coverimagefile = coverfile
                PictureBox1.ImageLocation = coverfile
                PictureBox1.Load()
                ChangeImageToolStripMenuItem.Enabled = True
                AddImageToolStripMenuItem.Enabled = False
                GoTo updateinterface
            End If
        Else

parsecoverfile:
            'Parse coverfile for image information
            If System.IO.File.Exists(coverfile) Then
                RichTextBox1.LoadFile(coverfile, RichTextBoxStreamType.PlainText)
                coverfiletext = RichTextBox1.Text
                startpos = InStr(coverfiletext, "<svg")
                If startpos <> 0 Then
                    Label4.Visible = True
                    Button1.Visible = True
                End If
                startpos = InStr(coverfiletext, "<img")
                If startpos <> 0 Then
                    startpos = InStr(startpos, coverfiletext, "src")
                    startpos = InStr(startpos, coverfiletext, Chr(34))
                    If startpos <> 0 Then
                        endpos = InStr(startpos + 1, coverfiletext, Chr(34))
                        If endpos <> 0 Then
                            relativecoverimagefile = Mid(coverfiletext, startpos + 1, endpos - startpos - 1)
                            coverimagefile = Path.GetDirectoryName(coverfile) + "\" + Replace(Mid(coverfiletext, startpos + 1, endpos - startpos - 1), "/", "\")
                            If System.IO.File.Exists(coverimagefile) Then
                                PictureBox1.ImageLocation = coverimagefile
                                PictureBox1.Load()
                                ChangeImageToolStripMenuItem.Enabled = True
                                AddImageToolStripMenuItem.Enabled = False
                                RichTextBox1.LoadFile(opffile, RichTextBoxStreamType.PlainText)
                                GoTo updateinterface
                            End If
                        End If
                    End If
                Else
                    startpos = InStr(coverfiletext, "<image")
                    If startpos <> 0 Then
                        startpos = InStr(startpos, coverfiletext, "href")
                        startpos = InStr(startpos, coverfiletext, Chr(34))
                        If startpos <> 0 Then
                            endpos = InStr(startpos + 1, coverfiletext, Chr(34))
                            If endpos <> 0 Then
                                relativecoverimagefile = Mid(coverfiletext, startpos + 1, endpos - startpos - 1)
                                coverimagefile = Path.GetDirectoryName(coverfile) + "\" + Replace(Mid(coverfiletext, startpos + 1, endpos - startpos - 1), "/", "\")
                                If System.IO.File.Exists(coverimagefile) Then
                                    PictureBox1.ImageLocation = coverimagefile
                                    PictureBox1.Load()
                                    ChangeImageToolStripMenuItem.Enabled = True
                                    AddImageToolStripMenuItem.Enabled = False
                                    RichTextBox1.LoadFile(opffile, RichTextBoxStreamType.PlainText)
                                    GoTo updateinterface
                                End If
                            End If
                        End If
                    Else
                        startpos = InStr(coverfiletext, "<svg:image")
                        If startpos <> 0 Then
                            startpos = InStr(startpos, coverfiletext, "href")
                            startpos = InStr(startpos, coverfiletext, Chr(34))
                            If startpos <> 0 Then
                                endpos = InStr(startpos + 1, coverfiletext, Chr(34))
                                If endpos <> 0 Then
                                    relativecoverimagefile = Mid(coverfiletext, startpos + 1, endpos - startpos - 1)
                                    coverimagefile = Path.GetDirectoryName(coverfile) + "\" + Replace(Mid(coverfiletext, startpos + 1, endpos - startpos - 1), "/", "\")
                                    If System.IO.File.Exists(coverimagefile) Then
                                        PictureBox1.ImageLocation = coverimagefile
                                        PictureBox1.Load()
                                        ChangeImageToolStripMenuItem.Enabled = True
                                        AddImageToolStripMenuItem.Enabled = False
                                        RichTextBox1.LoadFile(opffile, RichTextBoxStreamType.PlainText)
                                        GoTo updateinterface
                                    End If
                                End If
                            End If
                        End If
                    End If
                End If
            End If
        End If
didnotfindhref:
        ChangeImageToolStripMenuItem.Enabled = False
        AddImageToolStripMenuItem.Enabled = True

updateinterface:
    End Sub
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ' Check for Ionic.Zip.dll
        If Not System.IO.File.Exists(Application.StartupPath & "\Ionic.Zip.dll") Then
            MsgBox("Library file missing: Ionic.Zip.dll" + Chr(13) + "Please reinstall application.")
            End
        End If

        ' Check for external viewer
        Dim objIniFile As New IniFile(Application.StartupPath() + "\" + "EPubMetadataEditor.ini")
        Dim ViewerPath As String = _
            objIniFile.GetString("Viewer", "Path", "(none)")
        If ViewerPath <> "(none)" Then
            LinkLabel1.Text = "Change external viewer"
        End If

        Me.Width = 913
        Me.Height = 650

        tempdirectory = System.IO.Path.GetTempPath
        ChDir(tempdirectory)

        ComboBox1.SelectedIndex = -1
        ComboBox2.SelectedIndex = -1

        OpenFileDialog1.FileName = Command()
        If OpenFileDialog1.FileName <> "" Then
            'Check for quotation marks at start and end of commandline and delete them if found
            If ((Mid(OpenFileDialog1.FileName, 1, 1) = Chr(34)) And (Mid(OpenFileDialog1.FileName, Len(OpenFileDialog1.FileName), 1) = Chr(34))) Then
                OpenFileDialog1.FileName = Mid(OpenFileDialog1.FileName, 2, Len(OpenFileDialog1.FileName) - 2)
            End If
            OpenEPub()
            Button3.Enabled = False

            ' Check for external viewer
            If ViewerPath <> "(none)" Then
                Button8.Enabled = True
                LinkLabel1.Text = "Change external viewer"
            Else
                Button8.Enabled = False
            End If
        Else
            Button8.Enabled = False
        End If

        PictureBox1.AllowDrop = True

    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        If projectchanged Then
            DialogResult = Dialog1.ShowDialog
            If DialogResult = Windows.Forms.DialogResult.No Then
                ChDir(tempdirectory)
                If (My.Computer.FileSystem.DirectoryExists(ebookdirectory)) Then
                    My.Computer.FileSystem.DeleteDirectory(ebookdirectory, FileIO.DeleteDirectoryOption.DeleteAllContents)
                End If
                End
            ElseIf DialogResult = Windows.Forms.DialogResult.Yes Then
                SaveEpub()
                ChDir(tempdirectory)
                If (My.Computer.FileSystem.DirectoryExists(ebookdirectory)) Then
                    My.Computer.FileSystem.DeleteDirectory(ebookdirectory, FileIO.DeleteDirectoryOption.DeleteAllContents)
                End If
                End
            End If
        Else
            ChDir(tempdirectory)
            If (My.Computer.FileSystem.DirectoryExists(ebookdirectory)) Then
                My.Computer.FileSystem.DeleteDirectory(ebookdirectory, FileIO.DeleteDirectoryOption.DeleteAllContents)
            End If
            End
        End If
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        If projectchanged Then
            DialogResult = Dialog1.ShowDialog
            If DialogResult = Windows.Forms.DialogResult.Cancel Then
                Exit Sub
            End If
            If DialogResult = Windows.Forms.DialogResult.Yes Then
                SaveEpub()
            End If
        End If

        ' Delete previous temp directory (if it exists)
        If tempdirectory <> "" Then
            ChDir(tempdirectory)
            If ebookdirectory <> "" Then
                If (My.Computer.FileSystem.DirectoryExists(ebookdirectory)) Then
                    My.Computer.FileSystem.DeleteDirectory(ebookdirectory, FileIO.DeleteDirectoryOption.DeleteAllContents)
                End If
            End If
        End If

        'File chooser
        OpenFileDialog1.Filter = "EPub Files (*.epub)|*.epub|All files (*.*)|*.*"
        OpenFileDialog1.FilterIndex = 1
        OpenFileDialog1.FileName = ""
        If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            TextBox1.Text = ""
            TextBox2.Text = ""
            TextBox3.Text = ""
            TextBox4.Text = ""
            TextBox5.Text = ""
            TextBox6.Text = ""
            TextBox7.Text = ""
            TextBox8.Text = ""
            TextBox9.Text = ""
            TextBox10.Text = ""
            TextBox11.Text = ""
            TextBox12.Text = ""
            TextBox13.Text = ""
            TextBox14.Text = ""
            TextBox15.Text = ""
            TextBox16.Text = ""
            ComboBox1.SelectedIndex = -1
            ComboBox2.SelectedIndex = -1
            PictureBox1.Image = Nothing
            Label4.Visible = False
            Button1.Visible = False
            SaveImageAsToolStripMenuItem.Enabled = False
            AddImageToolStripMenuItem.Enabled = False
            ChangeImageToolStripMenuItem.Enabled = False
            OpenEPub()
            Button3.Enabled = False

            ' Check for external viewer
            Dim objIniFile As New IniFile(Application.StartupPath() + "\" + "EPubMetadataEditor.ini")
            Dim ViewerPath As String = _
                objIniFile.GetString("Viewer", "Path", "(none)")
            If ViewerPath <> "(none)" Then
                Button8.Enabled = True
                LinkLabel1.Text = "Change external viewer"
            Else
                Button8.Enabled = False
            End If
        End If

    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        SaveEpub()
    End Sub

    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
        TextBox12.Text = TextBox2.Text
    End Sub

    Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
        TextBox2.Text = TextBox12.Text
    End Sub

    Private Sub Button7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button7.Click
        Dim tempname, nextchar, newname As String
        Dim temppos As Integer
        tempname = TextBox2.Text
        If InStr(tempname, " ") <> 0 Then
            temppos = Len(tempname)
            nextchar = Mid(tempname, temppos, 1)
            While (nextchar <> " ")
                If temppos = 1 Then
                    GoTo errortext
                End If
                temppos = temppos - 1
                nextchar = Mid(tempname, temppos, 1)
            End While
            newname = Mid(tempname, temppos + 1) + ", " + Mid(tempname, 1, temppos - 1)
            TextBox12.Text = newname
        Else
            TextBox12.Text = tempname
        End If
errortext:
    End Sub

    Private Sub Button9_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button9.Click
        OpenFileDialog3.Filter = "EPub Files (*.epub)|*.epub"
        OpenFileDialog3.FilterIndex = 1
        OpenFileDialog3.FileName = ""
        If OpenFileDialog3.ShowDialog = Windows.Forms.DialogResult.OK Then
            Dim file As String
            For Each file In OpenFileDialog3.FileNames
                ListBox1.Items.Add(file)
            Next
            Button10.Enabled = True
        End If
    End Sub

    Private Sub Button10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button10.Click
        Dim filenum, x As Integer
        Dim startpos, endpos, lenheader, fileaspos, temploop, rolepos As Integer
        Dim metadatafile, rolestring, optionaltext As String

        ' do some checks first
        If ((CheckBox1.Checked = False) And (CheckBox2.Checked = False) And (CheckBox3.Checked = False) And (CheckBox4.Checked = False)) Then
            MsgBox("You need to check one of the batch task boxes!")
            Exit Sub
        End If

        TextBox1.Text = ""
        TextBox2.Text = ""
        TextBox3.Text = ""
        TextBox4.Text = ""
        TextBox5.Text = ""
        TextBox6.Text = ""
        TextBox7.Text = ""
        TextBox8.Text = ""
        TextBox9.Text = ""
        TextBox10.Text = ""
        TextBox11.Text = ""
        TextBox12.Text = ""
        TextBox13.Text = ""
        TextBox14.Text = ""
        TextBox15.Text = ""
        TextBox16.Text = ""
        ComboBox1.SelectedIndex = -1
        ComboBox2.SelectedIndex = -1
        PictureBox1.Image = Nothing
        SaveImageAsToolStripMenuItem.Enabled = False
        Label4.Visible = False
        Button1.Visible = False
        tempdirectory = System.IO.Path.GetTempPath
        ebookdirectory = tempdirectory + "EPUB"

        filenum = ListBox1.Items.Count
        ProgressBar1.Maximum = filenum - 1
        ProgressBar1.Visible = True

        For x = 1 To filenum
            ChDir(tempdirectory)
            ProgressBar1.Value = x - 1
            ProgressBar1.Update()
            Application.DoEvents()

            ' open file
            'Unzip epub to temp directory

            If (My.Computer.FileSystem.DirectoryExists(ebookdirectory)) Then
                'delete contents of temp directory
                DeleteDirContents(New IO.DirectoryInfo(ebookdirectory))
            Else
                MkDir(ebookdirectory)
            End If
            ChDir(ebookdirectory)

            Try
                Using zip As ZipFile = ZipFile.Read(ListBox1.Items(x - 1))
                    Dim item As ZipEntry
                    For Each item In zip
                        item.Extract()
                    Next
                End Using
            Catch ex1 As Exception
                Console.Error.WriteLine("exception: {0}", ex1.ToString)
            End Try

            'Search for .opf file
            searchResults = Directory.GetFiles(ebookdirectory, "*.opf", SearchOption.AllDirectories)

            'Open .opf file into RichTextBox
            If searchResults.Length < 1 Then
                DialogResult = MsgBox("Error: Metadata not found." + Chr(10) + "The ebook " + ListBox1.Items(x - 1) + " is malformed.", MsgBoxStyle.OkOnly, "EPub Metadata Editor")
                Return
            Else
                opffile = searchResults(0)
                opfdirectory = Path.GetDirectoryName(opffile)
                RichTextBox1.LoadFile(opffile, RichTextBoxStreamType.PlainText)
            End If

            'Extract metadata into textboxes
            metadatafile = RichTextBox1.Text

            'Get title
            startpos = InStr(metadatafile, "<dc:title")
            If startpos <> 0 Then
                endpos = InStr(metadatafile, "</dc:title>")
                lenheader = Len("<dc:title")
                If Mid(metadatafile, startpos + lenheader, 1) = ">" Then
                    TextBox1.Text = Mid(metadatafile, startpos + lenheader + 1, endpos - startpos - lenheader - 1)
                Else
                    'get optional attributes
                    fileaspos = InStr(startpos, metadatafile, "opf:file-as=")
                    If fileaspos <> 0 Then
                        For temploop = fileaspos + 13 To endpos
                            If Mid(metadatafile, temploop, 1) = Chr(34) Then
                                TextBox16.Text = Mid(metadatafile, fileaspos + 13, temploop - fileaspos - 13)
                            End If
                        Next
                    End If
                    For temploop = startpos To endpos
                        If Mid(metadatafile, temploop, 1) = ">" Then
                            TextBox1.Text = Mid(metadatafile, temploop + 1, endpos - temploop - 1)
                        End If
                    Next
                End If
            End If

            'Get creator
            startpos = InStr(metadatafile, "<dc:creator")
            If startpos <> 0 Then
                endpos = InStr(metadatafile, "</dc:creator>")
                lenheader = Len("<dc:creator")
                If Mid(metadatafile, startpos + lenheader, 1) = ">" Then
                    TextBox2.Text = Mid(metadatafile, startpos + lenheader + 1, endpos - startpos - lenheader - 1)
                Else
                    'Get optional attributes
                    fileaspos = InStr(startpos, metadatafile, "opf:file-as=")
                    If fileaspos <> 0 Then
                        For temploop = fileaspos + 13 To endpos
                            If Mid(metadatafile, temploop, 1) = Chr(34) Then
                                TextBox12.Text = Mid(metadatafile, fileaspos + 13, temploop - fileaspos - 13)
                                GoTo findrole1
                            End If
                        Next
                    End If
findrole1:
                    rolepos = InStr(startpos, metadatafile, "opf:role=")
                    If rolepos <> 0 Then
                        rolestring = Mid(metadatafile, rolepos + 10, 3)
                        If rolestring = "aut" Then
                            ComboBox1.SelectedIndex = 0
                        ElseIf rolestring = "edt" Then
                            ComboBox1.SelectedIndex = 1
                        ElseIf rolestring = "ill" Then
                            ComboBox1.SelectedIndex = 2
                        ElseIf rolestring = "trl" Then
                            ComboBox1.SelectedIndex = 3
                        Else
                            ComboBox1.SelectedIndex = 0
                        End If
                    Else
                        ComboBox1.SelectedIndex = 0
                    End If

                    For temploop = startpos To endpos
                        If Mid(metadatafile, temploop, 1) = ">" Then
                            TextBox2.Text = Mid(metadatafile, temploop + 1, endpos - temploop - 1)
                        End If
                    Next
                End If
            End If

            'Look for second creator
            startpos = InStr(endpos, metadatafile, "<dc:creator")
            If startpos <> 0 Then
                endpos = InStr(startpos, metadatafile, "</dc:creator>")
                lenheader = Len("<dc:creator")
                If Mid(metadatafile, startpos + lenheader, 1) = ">" Then
                    TextBox3.Text = Mid(metadatafile, startpos + lenheader, endpos - startpos - lenheader)
                Else
                    'Get optional attributes
                    fileaspos = InStr(startpos, metadatafile, "opf:file-as=")
                    If fileaspos <> 0 Then
                        For temploop = fileaspos + 13 To endpos
                            If Mid(metadatafile, temploop, 1) = Chr(34) Then
                                TextBox13.Text = Mid(metadatafile, fileaspos + 13, temploop - fileaspos - 13)
                                GoTo findrole2
                            End If
                        Next
                    End If
findrole2:
                    rolepos = InStr(startpos, metadatafile, "opf:role=")
                    If rolepos <> 0 Then
                        rolestring = Mid(metadatafile, rolepos + 10, 3)
                        If rolestring = "aut" Then ComboBox2.SelectedIndex = 0
                        If rolestring = "edt" Then ComboBox2.SelectedIndex = 1
                        If rolestring = "ill" Then ComboBox2.SelectedIndex = 2
                        If rolestring = "trl" Then ComboBox2.SelectedIndex = 3
                    End If

                    For temploop = startpos To endpos
                        If Mid(metadatafile, temploop, 1) = ">" Then
                            TextBox3.Text = Mid(metadatafile, temploop + 1, endpos - temploop - 1)
                        End If
                    Next
                End If
            End If

            If CheckBox1.Checked = True Then
                ' copy 'file as' to 'creator'
                If TextBox12.Text <> "" Then
                    TextBox2.Text = TextBox12.Text
                End If

                If TextBox13.Text <> "" Then
                    TextBox3.Text = TextBox13.Text
                End If
            End If

            If CheckBox2.Checked = True Then
                ' apply Title Case to 'title'
                TextBox1.Text = StrConv(TextBox1.Text, VbStrConv.ProperCase)
            End If

            If CheckBox3.Checked = True Then
                ' remove Title's 'File As'
                TextBox16.Text = ""
            End If

            If CheckBox4.Checked = True Then
                ' Autogenerate Creator's 'File as'
                Button7.PerformClick()
                If TextBox3.Text <> "" Then Button13.PerformClick()
            End If

            Application.DoEvents()

            ' save file
            'Output first creator
            startpos = InStr(metadatafile, "<dc:creator")
            If startpos <> 0 Then
                endpos = InStr(metadatafile, "</dc:creator>")
                lenheader = Len("<dc:creator")

                'If optional attributes
                If TextBox12.Text <> "" Then
                    optionaltext = ""
                    If ((ComboBox1.SelectedIndex = 0) Or (ComboBox1.SelectedIndex = -1)) Then optionaltext = " opf:role=" + Chr(34) + "aut" + Chr(34)
                    If ComboBox1.SelectedIndex = 1 Then optionaltext = " opf:role=" + Chr(34) + "edt" + Chr(34)
                    If ComboBox1.SelectedIndex = 2 Then optionaltext = " opf:role=" + Chr(34) + "ill" + Chr(34)
                    If ComboBox1.SelectedIndex = 3 Then optionaltext = " opf:role=" + Chr(34) + "trl" + Chr(34)
                    optionaltext = optionaltext + " opf:file-as=" + Chr(34) + TextBox12.Text + Chr(34) + ">"
                Else
                    optionaltext = ">"
                End If
                metadatafile = Mid(metadatafile, 1, startpos + lenheader - 1) + optionaltext + TextBox2.Text + Mid(metadatafile, endpos)

                'Output second creator?
                If TextBox3.Text <> "" Then
                    endpos = InStr(metadatafile, "</dc:creator>") 'find end of first creator
                    startpos = InStr(endpos, metadatafile, "<dc:creator") 'look for another one
                    'Get optional attributes
                    If TextBox13.Text <> "" Then
                        optionaltext = ""
                        If ((ComboBox2.SelectedIndex = 0) Or (ComboBox2.SelectedIndex = -1)) Then optionaltext = " opf:role=" + Chr(34) + "aut" + Chr(34)
                        If ComboBox2.SelectedIndex = 1 Then optionaltext = " opf:role=" + Chr(34) + "edt" + Chr(34)
                        If ComboBox2.SelectedIndex = 2 Then optionaltext = " opf:role=" + Chr(34) + "ill" + Chr(34)
                        If ComboBox2.SelectedIndex = 3 Then optionaltext = " opf:role=" + Chr(34) + "trl" + Chr(34)
                        optionaltext = optionaltext + " opf:file-as=" + Chr(34) + TextBox13.Text + Chr(34) + ">"
                    Else
                        optionaltext = ">"
                    End If
                    If startpos <> 0 Then
                        endpos = InStr(startpos, metadatafile, "</dc:creator>")
                        lenheader = Len("<dc:creator")
                        metadatafile = Mid(metadatafile, 1, startpos + lenheader - 1) + optionaltext + TextBox3.Text + Mid(metadatafile, endpos)
                    Else
                        'Original file did not have second creator
                        metadatafile = Mid(metadatafile, 1, endpos + 13) + Chr(13) + Chr(10) + Chr(9) + "<dc:creator" + optionaltext + TextBox3.Text + "</dc:creator>" + Chr(13) + Chr(10) + Mid(metadatafile, endpos + 14)
                    End If
                End If
            End If

            RichTextBox1.Text = metadatafile
            RichTextBox1.SaveFile(opffile, RichTextBoxStreamType.PlainText)

            'Zip temp directory (after deleting original file)
            Dim fi As New FileInfo(ListBox1.Items(x - 1))
            fi.Delete()

            Using zip As ZipFile = New ZipFile
                zip.AddDirectory(ebookdirectory)
                zip.Save(ListBox1.Items(x - 1))
            End Using

            TextBox1.Text = ""
            TextBox2.Text = ""
            TextBox3.Text = ""
            TextBox12.Text = ""
            TextBox13.Text = ""
            TextBox16.Text = ""
            ComboBox1.SelectedIndex = -1
            ComboBox2.SelectedIndex = -1

        Next
        ProgressBar1.Value = 0
        ProgressBar1.Update()
        ProgressBar1.Visible = False
        projectchanged = False
        Button3.Enabled = False
        Me.Text = "EPub Metadata Editor"
        TextBox1.Text = ""
        TextBox2.Text = ""
        TextBox3.Text = ""
        TextBox12.Text = ""
        TextBox13.Text = ""
        TextBox16.Text = ""
        ComboBox1.SelectedIndex = -1
        ComboBox2.SelectedIndex = -1
        DialogResult = MsgBox("All done!", MsgBoxStyle.OkOnly, "EPub Metadata Editor")
        Button10.Enabled = False

        If (My.Computer.FileSystem.DirectoryExists(ebookdirectory)) Then
            'delete contents of temp directory
            DeleteDirContents(New IO.DirectoryInfo(ebookdirectory))
        End If
    End Sub

    Private Sub Button11_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button11.Click
        ListBox1.Items.Clear()
        Button10.Enabled = False
    End Sub

    Private Sub SaveImageAsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveImageAsToolStripMenuItem.Click
        SaveFileDialog1.Filter = "JPEG image (*.jpg)|*.jpg|All files (*.*)|*.*"
        SaveFileDialog1.FilterIndex = 1
        SaveFileDialog1.FileName = "cover.jpg"
        If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            System.IO.File.Copy(coverimagefile, SaveFileDialog1.FileName, True)
        End If
    End Sub

    Private Sub Button12_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button12.Click
        AboutBox1.ShowDialog()
    End Sub

    Private Sub Button15_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button15.Click
        TextBox13.Text = TextBox3.Text
        projectchanged = True
        Button3.Enabled = True
        Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
    End Sub

    Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
        Dim tempname, nextchar, newname As String
        Dim temppos As Integer
        tempname = TextBox3.Text
        If InStr(tempname, " ") <> 0 Then
            temppos = Len(tempname)
            If temppos = 0 Then GoTo errortext
            nextchar = Mid(tempname, temppos, 1)
            While (nextchar <> " ")
                If temppos = 1 Then
                    GoTo errortext
                End If
                temppos = temppos - 1
                nextchar = Mid(tempname, temppos, 1)
            End While

            newname = Mid(tempname, temppos + 1) + ", " + Mid(tempname, 1, temppos - 1)
            TextBox13.Text = newname
        Else
            TextBox13.Text = tempname
        End If
        projectchanged = True
        Button3.Enabled = True
        Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
errortext:
    End Sub

    Private Sub Button14_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button14.Click
        TextBox3.Text = TextBox13.Text
        projectchanged = True
        Button3.Enabled = True
        Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
    End Sub

    Private Sub ChangeImageToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChangeImageToolStripMenuItem.Click
        OpenFileDialog2.Filter = "Image Files (*.jpg)|*.jpg|All files (*.*)|*.*"
        OpenFileDialog2.FilterIndex = 1
        OpenFileDialog2.FileName = ""
        If OpenFileDialog2.ShowDialog = Windows.Forms.DialogResult.OK Then
            System.IO.File.Copy(OpenFileDialog2.FileName, coverimagefile, True)
            PictureBox1.Load()
            projectchanged = True
            Button3.Enabled = True
            Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
        End If
    End Sub

    Private Sub AddImageToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddImageToolStripMenuItem.Click
        Dim outputfile, metadatafile, newlineandspace, insertion As String
        Dim startpos, insertpos As Integer

        OpenFileDialog2.Filter = "Image Files (*.jpg)|*.jpg|All files (*.*)|*.*"
        OpenFileDialog2.FilterIndex = 1
        OpenFileDialog2.FileName = ""
        If OpenFileDialog2.ShowDialog = Windows.Forms.DialogResult.OK Then
            'copy to outputfile
            outputfile = "cover" + Path.GetExtension(OpenFileDialog2.FileName)
            coverimagefile = outputfile
            System.IO.File.Copy(OpenFileDialog2.FileName, opfdirectory + "\" + outputfile, True)
            PictureBox1.ImageLocation = opfdirectory + "\" + outputfile
            PictureBox1.Load()

            'output html file
            RichTextBox1.Text = ""
            RichTextBox1.Text = RichTextBox1.Text + "<?xml version='1.0' encoding='utf-8'?>" + Chr(10)
            RichTextBox1.Text = RichTextBox1.Text + "<html xmlns=" + Chr(34) + "http://www.w3.org/1999/xhtml" + Chr(34) + " xml:lang=" + Chr(34) + "en" + Chr(34) + ">" + Chr(10)
            RichTextBox1.Text = RichTextBox1.Text + "            <head>" + Chr(10)
            RichTextBox1.Text = RichTextBox1.Text + "                <meta http-equiv=" + Chr(34) + "Content-Type" + Chr(34) + " content=" + Chr(34) + "text/html; charset=UTF-8" + Chr(34) + "/>" + Chr(10)
            RichTextBox1.Text = RichTextBox1.Text + "                <meta name=" + Chr(34) + "calibre:cover" + Chr(34) + " content=" + Chr(34) + "true" + Chr(34) + "/>" + Chr(10)
            RichTextBox1.Text = RichTextBox1.Text + "                <title>Cover</title>" + Chr(10)
            RichTextBox1.Text = RichTextBox1.Text + "                <style type=" + Chr(34) + "text/css" + Chr(34) + " title=" + Chr(34) + "override_css" + Chr(34) + ">" + Chr(10)
            RichTextBox1.Text = RichTextBox1.Text + "                    @page {padding: 0pt; margin:0pt}" + Chr(10)
            RichTextBox1.Text = RichTextBox1.Text + "                    body { text-align: center; padding:0pt; margin: 0pt; }" + Chr(10)
            RichTextBox1.Text = RichTextBox1.Text + "                    div { padding:0pt; margin: 0pt; }" + Chr(10)
            RichTextBox1.Text = RichTextBox1.Text + "                </style>" + Chr(10)
            RichTextBox1.Text = RichTextBox1.Text + "            </head>" + Chr(10)
            RichTextBox1.Text = RichTextBox1.Text + "            <body>" + Chr(10)
            RichTextBox1.Text = RichTextBox1.Text + "                <div>" + Chr(10)
            RichTextBox1.Text = RichTextBox1.Text + "                    <img src=" + Chr(34) + outputfile + Chr(34) + " alt=" + Chr(34) + "cover" + Chr(34) + " style=" + Chr(34) + "height: 100%" + Chr(34) + "/>" + Chr(10)
            RichTextBox1.Text = RichTextBox1.Text + "                </div>" + Chr(10)
            RichTextBox1.Text = RichTextBox1.Text + "            </body>" + Chr(10)
            RichTextBox1.Text = RichTextBox1.Text + "        </html>"
            RichTextBox1.SaveFile(opfdirectory + "\titlepage.xhtml", RichTextBoxStreamType.PlainText)

            'make changes to opf file
            RichTextBox1.LoadFile(opffile, RichTextBoxStreamType.PlainText)

            'add item to metadata
            metadatafile = RichTextBox1.Text
            startpos = InStr(metadatafile, "</dc:title>")
            If startpos <> 0 Then
                insertpos = InStr(startpos + 1, metadatafile, "<")
                If insertpos <> 0 Then
                    newlineandspace = Mid(metadatafile, startpos + 11, insertpos - startpos - 11)
                    insertion = newlineandspace + "<meta name=" + Chr(34) + "cover" + Chr(34) + " content=" + Chr(34) + "cover" + Chr(34) + "/>" + newlineandspace
                    metadatafile = Mid(metadatafile, 1, startpos + 10) + insertion + Mid(metadatafile, insertpos, Len(metadatafile) - insertpos + 1)
                    RichTextBox1.Text = metadatafile
                End If
            End If

            'add items to manifest
            metadatafile = RichTextBox1.Text
            startpos = InStr(metadatafile, "<manifest>")
            If startpos <> 0 Then
                insertpos = InStr(startpos + 1, metadatafile, "<")
                If insertpos <> 0 Then
                    newlineandspace = Mid(metadatafile, startpos + 10, insertpos - startpos - 10)
                    insertion = newlineandspace + "<item href=" + Chr(34) + outputfile + Chr(34) + " id=" + Chr(34) + "cover" + Chr(34) + " media-type=" + Chr(34) + "image/jpeg" + Chr(34) + "/>" + newlineandspace
                    insertion = insertion + "<item href=" + Chr(34) + "titlepage.xhtml" + Chr(34) + " id=" + Chr(34) + "titlepage" + Chr(34) + " media-type=" + Chr(34) + "application/xhtml+xml" + Chr(34) + "/>" + newlineandspace
                    metadatafile = Mid(metadatafile, 1, startpos + 9) + insertion + Mid(metadatafile, insertpos, Len(metadatafile) - insertpos + 1)
                    RichTextBox1.Text = metadatafile
                End If
            End If

            'add item to spine
            metadatafile = RichTextBox1.Text
            startpos = InStr(metadatafile, "<spine")
            If startpos <> 0 Then
                insertpos = InStr(startpos + 1, metadatafile, "<")
                If insertpos <> 0 Then
                    startpos = insertpos
                    While (Mid(metadatafile, startpos, 1) <> Chr(10))
                        startpos = startpos - 1
                    End While
                    newlineandspace = Mid(metadatafile, startpos, insertpos - startpos)
                    insertion = "<itemref idref=" + Chr(34) + "titlepage" + Chr(34) + "/>"
                    metadatafile = Mid(metadatafile, 1, startpos - 1) + newlineandspace + insertion + newlineandspace + Mid(metadatafile, insertpos, Len(metadatafile) - insertpos + 1)
                    RichTextBox1.Text = metadatafile
                End If
            End If

            'add reference to guide
            metadatafile = RichTextBox1.Text
            startpos = InStr(metadatafile, "<guide>")
            If startpos <> 0 Then
                insertpos = InStr(startpos + 1, metadatafile, "<")
                If insertpos <> 0 Then
                    newlineandspace = Mid(metadatafile, startpos + 7, insertpos - startpos - 7)
                    insertion = newlineandspace + "<reference href=" + Chr(34) + "titlepage.xhtml" + Chr(34) + " type=" + Chr(34) + "cover" + Chr(34) + " title=" + Chr(34) + "Cover" + Chr(34) + "/>" + newlineandspace
                    metadatafile = Mid(metadatafile, 1, startpos + 6) + insertion + Mid(metadatafile, insertpos, Len(metadatafile) - insertpos + 1)
                    RichTextBox1.Text = metadatafile
                End If
            Else
                'look for <guide/> and delete it
                metadatafile = metadatafile.Replace("<guide/>", "")

                'now create <guide>
                startpos = InStr(metadatafile, "</package>")
                If startpos <> 0 Then
                    insertion = "<guide>" + Chr(10) + "    <reference href=" + Chr(34) + "titlepage.xhtml" + Chr(34) + " type=" + Chr(34) + "cover" + Chr(34) + " title=" + Chr(34) + "Cover" + Chr(34) + "/>" + Chr(10) + "</guide>" + Chr(10)
                    metadatafile = Mid(metadatafile, 1, startpos - 1) + insertion + Mid(metadatafile, startpos, Len(metadatafile) - startpos + 1)
                    RichTextBox1.Text = metadatafile
                End If
            End If

            'save opf file
            RichTextBox1.SaveFile(opffile, RichTextBoxStreamType.PlainText)

            'update interface
            projectchanged = True
            Button3.Enabled = True
            SaveImageAsToolStripMenuItem.Enabled = True
            ChangeImageToolStripMenuItem.Enabled = True
            AddImageToolStripMenuItem.Enabled = False
            Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
        End If
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'output html file
        RichTextBox1.Text = ""
        RichTextBox1.Text = RichTextBox1.Text + "<?xml version='1.0' encoding='utf-8'?>" + Chr(10)
        RichTextBox1.Text = RichTextBox1.Text + "<html xmlns=" + Chr(34) + "http://www.w3.org/1999/xhtml" + Chr(34) + " xml:lang=" + Chr(34) + "en" + Chr(34) + ">" + Chr(10)
        RichTextBox1.Text = RichTextBox1.Text + "            <head>" + Chr(10)
        RichTextBox1.Text = RichTextBox1.Text + "                <meta http-equiv=" + Chr(34) + "Content-Type" + Chr(34) + " content=" + Chr(34) + "text/html; charset=UTF-8" + Chr(34) + "/>" + Chr(10)
        RichTextBox1.Text = RichTextBox1.Text + "                <meta name=" + Chr(34) + "calibre:cover" + Chr(34) + " content=" + Chr(34) + "true" + Chr(34) + "/>" + Chr(10)
        RichTextBox1.Text = RichTextBox1.Text + "                <title>Cover</title>" + Chr(10)
        RichTextBox1.Text = RichTextBox1.Text + "                <style type=" + Chr(34) + "text/css" + Chr(34) + " title=" + Chr(34) + "override_css" + Chr(34) + ">" + Chr(10)
        RichTextBox1.Text = RichTextBox1.Text + "                    @page {padding: 0pt; margin:0pt}" + Chr(10)
        RichTextBox1.Text = RichTextBox1.Text + "                    body { text-align: center; padding:0pt; margin: 0pt; }" + Chr(10)
        RichTextBox1.Text = RichTextBox1.Text + "                    div { padding:0pt; margin: 0pt; }" + Chr(10)
        RichTextBox1.Text = RichTextBox1.Text + "                </style>" + Chr(10)
        RichTextBox1.Text = RichTextBox1.Text + "            </head>" + Chr(10)
        RichTextBox1.Text = RichTextBox1.Text + "            <body>" + Chr(10)
        RichTextBox1.Text = RichTextBox1.Text + "                <div>" + Chr(10)
        RichTextBox1.Text = RichTextBox1.Text + "                    <img src=" + Chr(34) + relativecoverimagefile + Chr(34) + " alt=" + Chr(34) + "cover" + Chr(34) + " style=" + Chr(34) + "height: 100%" + Chr(34) + "/>" + Chr(10)
        RichTextBox1.Text = RichTextBox1.Text + "                </div>" + Chr(10)
        RichTextBox1.Text = RichTextBox1.Text + "            </body>" + Chr(10)
        RichTextBox1.Text = RichTextBox1.Text + "        </html>"
        RichTextBox1.SaveFile(coverfile, RichTextBoxStreamType.PlainText)
        Button1.Visible = False
        Label4.Visible = False
        projectchanged = True
        Button3.Enabled = True
        Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
    End Sub
    Private Function FileInUse(ByVal sFile As String) As Boolean
        If System.IO.File.Exists(sFile) Then
            Try
                Dim F As Short = FreeFile()
                FileOpen(F, sFile, OpenMode.Binary, OpenAccess.ReadWrite, OpenShare.LockReadWrite)
                FileClose(F)
            Catch
                Return True
            End Try
        End If
    End Function

    Private Sub Button8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button8.Click
        Dim tempfilename As String
        Dim objIniFile As New IniFile(Application.StartupPath() + "\" + "EPubMetadataEditor.ini")
        Dim ViewerPath As String = _
            objIniFile.GetString("Viewer", "Path", "(none)")
        If ViewerPath <> "(none)" Then

            Using zip As ZipFile = New ZipFile
                zip.AddDirectory(ebookdirectory)
                tempfilename = tempdirectory & "\" & System.IO.Path.GetFileName(OpenFileDialog1.FileName)
                zip.Save(tempfilename)
            End Using

            Dim myProcess As System.Diagnostics.Process = _
                  New System.Diagnostics.Process()
            myProcess.StartInfo.FileName = ViewerPath
            myProcess.StartInfo.Arguments = Chr(34) + tempfilename + Chr(34)
            myProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal
            myProcess.Start()
            myProcess.WaitForExit()
            myProcess.Close()
            System.IO.File.Delete(tempfilename)
        End If
    End Sub

    Private Sub Button16_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button16.Click
        Me.Width = 1257
        Button16.Visible = False
    End Sub

    Private Sub Button17_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button17.Click
        Me.Width = 913
        Button16.Visible = True
    End Sub

    Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
        Dim viewerfilename, inifilename As String
        inifilename = Application.StartupPath() + "\" + "EPubMetadataEditor.ini"
        If System.IO.File.Exists(inifilename) = False Then
            Dim fs As New FileStream(inifilename, FileMode.Create, FileAccess.Write)
            Dim s As New StreamWriter(fs)
            s.WriteLine("[Viewer]")
            s.WriteLine("Path=" + Chr(34) + "(none)" + Chr(34))
            s.Close()
        End If

        Dim objIniFile As New IniFile(inifilename)
        viewerfilename = objIniFile.GetString("Viewer", "Path", "(none)")
        If viewerfilename <> "(none)" Then
            OpenFileDialog4.FileName = Path.GetFileName(viewerfilename)
            OpenFileDialog4.InitialDirectory = Path.GetDirectoryName(viewerfilename)
        Else
            OpenFileDialog4.FileName = ""
        End If
        OpenFileDialog4.Filter = "Executable Files (*.exe)|*.exe|All Files (*.*)|*.*"
        OpenFileDialog4.FilterIndex = 1

        If OpenFileDialog4.ShowDialog = Windows.Forms.DialogResult.OK Then
            objIniFile.WriteString("Viewer", "Path", Chr(34) + OpenFileDialog4.FileName + Chr(34))
            LinkLabel1.Text = "Change external editor"
            Button8.Enabled = Button23.Enabled
        End If
    End Sub

    Private Sub Button18_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button18.Click
        TextBox16.Text = ""
        projectchanged = True
        Button3.Enabled = True
        Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
    End Sub

    Private Sub Button19_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button19.Click
        Dim metadatafile As String

        fileeditorreturn = False
        filecontents = ""
        Form2.Button3.Visible = True
        Form2.RichTextBox1.LoadFile(opffile, RichTextBoxStreamType.PlainText)
        Form2.ShowDialog()
        If fileeditorreturn = True Then
            RichTextBox1.Text = filecontents
            RichTextBox1.SaveFile(opffile, RichTextBoxStreamType.PlainText)
            projectchanged = True
            Button3.Enabled = True
            Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"

            ' Need to update metadata
            RichTextBox1.LoadFile(opffile, RichTextBoxStreamType.PlainText)
            metadatafile = RichTextBox1.Text
            ExtractMetadata(metadatafile)
        End If
    End Sub

    Private Sub Button20_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button20.Click
        fileeditorreturn = False
        filecontents = ""
        Form2.Button3.Visible = False
        Form2.RichTextBox1.LoadFile(tocfile, RichTextBoxStreamType.PlainText)
        Form2.ShowDialog()
        If fileeditorreturn = True Then
            RichTextBox1.Text = filecontents
            RichTextBox1.SaveFile(tocfile, RichTextBoxStreamType.PlainText)
            projectchanged = True
            Button3.Enabled = True
            Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
        End If
    End Sub

    Private Sub Button21_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button21.Click
        TextBox16.Text = TextBox1.Text
        projectchanged = True
        Button3.Enabled = True
        Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
    End Sub

    Private Sub Button22_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button22.Click
        TextBox1.Text = TextBox16.Text
        projectchanged = True
        Button3.Enabled = True
        Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
    End Sub

    Private Sub Button23_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button23.Click
        Dim tempstring As String
        Dim startpos, endpos, currpos, doclength, depth, textpos, nodenums As Integer
        Dim currentrootnode(5) As Integer
        Dim uplevel, downlevel As Boolean

        RichTextBox1.LoadFile(tocfile, RichTextBoxStreamType.PlainText)

        'Search for doctitle
        tempstring = LCase(RichTextBox1.Text)
        startpos = InStr(tempstring, "<doctitle>")
        If startpos <> 0 Then
            currpos = InStr(startpos, tempstring, "<text>")
            If currpos <> 0 Then
                endpos = InStr(currpos, tempstring, "</text>")
                If endpos <> 0 Then
                    Form3.Text = Mid(RichTextBox1.Text, currpos + 6, endpos - currpos - 6)
                End If
            End If
        End If

        'Search for author
        startpos = InStr(tempstring, "<docauthor>")
        If startpos <> 0 Then
            currpos = InStr(startpos, tempstring, "<text>")
            If currpos <> 0 Then
                endpos = InStr(currpos, tempstring, "</text>")
                If endpos <> 0 Then
                    Form3.Text = Form3.Text + " by " + Mid(RichTextBox1.Text, currpos + 6, endpos - currpos - 6)
                End If
            End If
        End If

        Dim NewNode() As VistaNode
        nodenums = 0
        Form3.VistaTreeView1.Nodes.Clear()
        doclength = Len(tempstring)
        depth = 0
        uplevel = False
        currentrootnode(0) = -1
        currentrootnode(1) = -1
        currentrootnode(2) = -1
        currentrootnode(3) = -1
        currentrootnode(4) = -1
        currentrootnode(5) = -1

        startpos = InStr(tempstring, "<navmap>")
        currpos = startpos
        If startpos <> 0 Then
            While currpos <= doclength
                currpos = currpos + 1
                If Mid(tempstring, currpos, 9) = "<navpoint" Then
                    If uplevel = True Then
                        depth = depth + 1
                    End If
                    uplevel = True
                    downlevel = False
                    currentrootnode(depth) = currentrootnode(depth) + 1
                    ' Look for node label
                    textpos = InStr(currpos, tempstring, "<text>")
                    If textpos <> 0 Then
                        endpos = InStr(textpos, tempstring, "</text>")
                        If endpos <> 0 Then
                            If depth = 0 Then
                                nodenums = nodenums + 1
                                ReDim NewNode(nodenums)
                                NewNode(nodenums) = New VistaNode
                                NewNode(nodenums).Text = Mid(RichTextBox1.Text, textpos + 6, endpos - textpos - 6)
                                Form3.VistaTreeView1.Nodes.Add(NewNode(nodenums))
                            End If
                            If depth = 1 Then
                                nodenums = nodenums + 1
                                ReDim NewNode(nodenums)
                                NewNode(nodenums) = New VistaNode
                                NewNode(nodenums).Text = Mid(RichTextBox1.Text, textpos + 6, endpos - textpos - 6)
                                Form3.VistaTreeView1.Nodes(currentrootnode(0)).Nodes.Add(NewNode(nodenums))
                            End If
                            If depth = 2 Then
                                nodenums = nodenums + 1
                                ReDim NewNode(nodenums)
                                NewNode(nodenums) = New VistaNode
                                NewNode(nodenums).Text = Mid(RichTextBox1.Text, textpos + 6, endpos - textpos - 6)
                                Form3.VistaTreeView1.Nodes(currentrootnode(0)).Nodes(currentrootnode(1)).Nodes.Add(NewNode(nodenums))
                            End If
                            If depth = 3 Then
                                nodenums = nodenums + 1
                                ReDim NewNode(nodenums)
                                NewNode(nodenums) = New VistaNode
                                NewNode(nodenums).Text = Mid(RichTextBox1.Text, textpos + 6, endpos - textpos - 6)
                                Form3.VistaTreeView1.Nodes(currentrootnode(0)).Nodes(currentrootnode(1)).Nodes(currentrootnode(2)).Nodes.Add(NewNode(nodenums))
                            End If
                            If depth = 4 Then
                                nodenums = nodenums + 1
                                ReDim NewNode(nodenums)
                                NewNode(nodenums) = New VistaNode
                                NewNode(nodenums).Text = Mid(RichTextBox1.Text, textpos + 6, endpos - textpos - 6)
                                Form3.VistaTreeView1.Nodes(currentrootnode(0)).Nodes(currentrootnode(1)).Nodes(currentrootnode(2)).Nodes(currentrootnode(3)).Nodes.Add(NewNode(nodenums))
                            End If
                            If depth = 5 Then
                                nodenums = nodenums + 1
                                ReDim NewNode(nodenums)
                                NewNode(nodenums) = New VistaNode
                                NewNode(nodenums).Text = Mid(RichTextBox1.Text, textpos + 6, endpos - textpos - 6)
                                Form3.VistaTreeView1.Nodes(currentrootnode(0)).Nodes(currentrootnode(1)).Nodes(currentrootnode(2)).Nodes(currentrootnode(3)).Nodes(currentrootnode(4)).Nodes.Add(NewNode(nodenums))
                            End If
                            If depth = 6 Then
                                nodenums = nodenums + 1
                                ReDim NewNode(nodenums)
                                NewNode(nodenums) = New VistaNode
                                NewNode(nodenums).Text = Mid(RichTextBox1.Text, textpos + 6, endpos - textpos - 6)
                                Form3.VistaTreeView1.Nodes(currentrootnode(0)).Nodes(currentrootnode(1)).Nodes(currentrootnode(2)).Nodes(currentrootnode(3)).Nodes(currentrootnode(4)).Nodes(currentrootnode(5)).Nodes.Add(NewNode(nodenums))
                            End If
                        End If
                    End If
                End If

                If Mid(tempstring, currpos, 11) = "</navpoint>" Then
                    If downlevel = True Then
                        currentrootnode(depth) = -1
                        depth = depth - 1
                    End If
                    downlevel = True
                    uplevel = False
                End If
            End While
        End If

        Dim currentNode As TreeNode = Form3.VistaTreeView1.GetNodeAt(0, 0)
        Form3.VistaTreeView1.ExpandAll()
        If Not currentNode Is Nothing Then currentNode.EnsureVisible()
        Form3.ToolStripMenuItem1.Checked = True
        Button23.Enabled = False
        Form3.Show()
    End Sub

    Private Sub Button24_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button24.Click
        fileeditorreturn = False
        filecontents = ""
        Form2.Button3.Visible = True
        Form2.RichTextBox1.LoadFile(pagemapfile, RichTextBoxStreamType.PlainText)
        Form2.ShowDialog()
        If fileeditorreturn = True Then
            RichTextBox1.Text = filecontents
            RichTextBox1.SaveFile(pagemapfile, RichTextBoxStreamType.PlainText)
            projectchanged = True
            Button3.Enabled = True
            Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
        End If
    End Sub

    Private Sub Button25_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button25.Click
        TextBox1.Text = StrConv(TextBox1.Text, VbStrConv.ProperCase)
    End Sub

    Private Sub PictureBox1_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles PictureBox1.DragEnter
        If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            e.Effect = DragDropEffects.All
        Else
            e.Effect = DragDropEffects.None
        End If
    End Sub

    Private Sub PictureBox1_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles PictureBox1.DragDrop
        Dim MyFiles() As String
        Dim i As Integer
        Dim metadatafile, newlineandspace, insertion As String
        Dim startpos, insertpos As Integer

        If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            ' Assign the file(s) to an array.
            MyFiles = e.Data.GetData(DataFormats.FileDrop)
        Else
            Exit Sub
        End If

        ' Loop through the array
        For i = 0 To MyFiles.Length - 1
            If IO.File.Exists(coverimagefile) Then
                IO.File.Delete(coverimagefile)
            Else
                'need to create a new cover file
                coverimagefile = opfdirectory + "\cover.jpg"

                'output html file
                RichTextBox1.Text = ""
                RichTextBox1.Text = RichTextBox1.Text + "<?xml version='1.0' encoding='utf-8'?>" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "<html xmlns=" + Chr(34) + "http://www.w3.org/1999/xhtml" + Chr(34) + " xml:lang=" + Chr(34) + "en" + Chr(34) + ">" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "            <head>" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "                <meta http-equiv=" + Chr(34) + "Content-Type" + Chr(34) + " content=" + Chr(34) + "text/html; charset=UTF-8" + Chr(34) + "/>" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "                <meta name=" + Chr(34) + "calibre:cover" + Chr(34) + " content=" + Chr(34) + "true" + Chr(34) + "/>" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "                <title>Cover</title>" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "                <style type=" + Chr(34) + "text/css" + Chr(34) + " title=" + Chr(34) + "override_css" + Chr(34) + ">" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "                    @page {padding: 0pt; margin:0pt}" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "                    body { text-align: center; padding:0pt; margin: 0pt; }" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "                    div { padding:0pt; margin: 0pt; }" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "                </style>" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "            </head>" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "            <body>" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "                <div>" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "                    <img src=" + Chr(34) + "cover.jpg" + Chr(34) + " alt=" + Chr(34) + "cover" + Chr(34) + " style=" + Chr(34) + "height: 100%" + Chr(34) + "/>" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "                </div>" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "            </body>" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "        </html>"
                RichTextBox1.SaveFile(opfdirectory + "\titlepage.xhtml", RichTextBoxStreamType.PlainText)

                'make changes to opf file
                RichTextBox1.LoadFile(opffile, RichTextBoxStreamType.PlainText)

                'add item to metadata
                metadatafile = RichTextBox1.Text
                startpos = InStr(metadatafile, "</dc:title>")
                If startpos <> 0 Then
                    insertpos = InStr(startpos + 1, metadatafile, "<")
                    If insertpos <> 0 Then
                        newlineandspace = Mid(metadatafile, startpos + 11, insertpos - startpos - 11)
                        insertion = newlineandspace + "<meta name=" + Chr(34) + "cover" + Chr(34) + " content=" + Chr(34) + "cover" + Chr(34) + "/>" + newlineandspace
                        metadatafile = Mid(metadatafile, 1, startpos + 10) + insertion + Mid(metadatafile, insertpos, Len(metadatafile) - insertpos + 1)
                        RichTextBox1.Text = metadatafile
                    End If
                End If

                'add items to manifest
                metadatafile = RichTextBox1.Text
                startpos = InStr(metadatafile, "<manifest>")
                If startpos <> 0 Then
                    insertpos = InStr(startpos + 1, metadatafile, "<")
                    If insertpos <> 0 Then
                        newlineandspace = Mid(metadatafile, startpos + 10, insertpos - startpos - 10)
                        insertion = newlineandspace + "<item href=" + Chr(34) + "cover.jpg" + Chr(34) + " id=" + Chr(34) + "cover" + Chr(34) + " media-type=" + Chr(34) + "image/jpeg" + Chr(34) + "/>" + newlineandspace
                        insertion = insertion + "<item href=" + Chr(34) + "titlepage.xhtml" + Chr(34) + " id=" + Chr(34) + "titlepage" + Chr(34) + " media-type=" + Chr(34) + "application/xhtml+xml" + Chr(34) + "/>" + newlineandspace
                        metadatafile = Mid(metadatafile, 1, startpos + 9) + insertion + Mid(metadatafile, insertpos, Len(metadatafile) - insertpos + 1)
                        RichTextBox1.Text = metadatafile
                    End If
                End If

                'add item to spine
                metadatafile = RichTextBox1.Text
                startpos = InStr(metadatafile, "<spine")
                If startpos <> 0 Then
                    insertpos = InStr(startpos + 1, metadatafile, "<")
                    If insertpos <> 0 Then
                        startpos = insertpos
                        While (Mid(metadatafile, startpos, 1) <> Chr(10))
                            startpos = startpos - 1
                        End While
                        newlineandspace = Mid(metadatafile, startpos, insertpos - startpos)
                        insertion = "<itemref idref=" + Chr(34) + "titlepage" + Chr(34) + "/>"
                        metadatafile = Mid(metadatafile, 1, startpos - 1) + newlineandspace + insertion + newlineandspace + Mid(metadatafile, insertpos, Len(metadatafile) - insertpos + 1)
                        RichTextBox1.Text = metadatafile
                    End If
                End If

                'add reference to guide
                metadatafile = RichTextBox1.Text
                startpos = InStr(metadatafile, "<guide>")
                If startpos <> 0 Then
                    insertpos = InStr(startpos + 1, metadatafile, "<")
                    If insertpos <> 0 Then
                        newlineandspace = Mid(metadatafile, startpos + 7, insertpos - startpos - 7)
                        insertion = newlineandspace + "<reference href=" + Chr(34) + "titlepage.xhtml" + Chr(34) + " type=" + Chr(34) + "cover" + Chr(34) + " title=" + Chr(34) + "Cover" + Chr(34) + "/>" + newlineandspace
                        metadatafile = Mid(metadatafile, 1, startpos + 6) + insertion + Mid(metadatafile, insertpos, Len(metadatafile) - insertpos + 1)
                        RichTextBox1.Text = metadatafile
                    End If
                Else
                    'look for <guide/> and delete it
                    metadatafile = metadatafile.Replace("<guide/>", "")

                    'now create <guide>
                    startpos = InStr(metadatafile, "</package>")
                    If startpos <> 0 Then
                        insertion = "<guide>" + Chr(10) + "    <reference href=" + Chr(34) + "titlepage.xhtml" + Chr(34) + " type=" + Chr(34) + "cover" + Chr(34) + " title=" + Chr(34) + "Cover" + Chr(34) + "/>" + Chr(10) + "</guide>" + Chr(10)
                        metadatafile = Mid(metadatafile, 1, startpos - 1) + insertion + Mid(metadatafile, startpos, Len(metadatafile) - startpos + 1)
                        RichTextBox1.Text = metadatafile
                    End If
                End If

                'save opf file
                RichTextBox1.SaveFile(opffile, RichTextBoxStreamType.PlainText)

            End If
            IO.File.Copy(MyFiles(i), coverimagefile)
            PictureBox1.ImageLocation = coverimagefile
            PictureBox1.Load()
            ChangeImageToolStripMenuItem.Enabled = True
            AddImageToolStripMenuItem.Enabled = False
            projectchanged = True
            Button3.Enabled = True
            Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
        Next
    End Sub

    Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseDown
        If Not PictureBox1.ImageLocation Is Nothing Then
            ' Set a flag to show that the mouse is down.
            m_MouseIsDown = True
        End If
    End Sub

    Private Sub PictureBox1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
        If m_MouseIsDown Then
            ' Initiate dragging
            Dim DropList As New System.Collections.Specialized.StringCollection
            Dim DragPaths As New DataObject()
            DropList.Add(PictureBox1.ImageLocation)
            DragPaths.SetFileDropList(DropList)
            PictureBox1.DoDragDrop(DragPaths, DragDropEffects.All)
        End If
        m_MouseIsDown = False
    End Sub

    Private Sub PasteImageToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PasteImageToolStripMenuItem.Click
        Dim pic As Image
        Dim metadatafile, newlineandspace, insertion As String
        Dim startpos, insertpos As Integer

        If Clipboard.ContainsImage Then
            pic = Clipboard.GetImage
            If coverimagefile = "" Then
                'need to create a new cover file
                coverimagefile = opfdirectory + "\cover.jpg"

                'output html file
                RichTextBox1.Text = ""
                RichTextBox1.Text = RichTextBox1.Text + "<?xml version='1.0' encoding='utf-8'?>" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "<html xmlns=" + Chr(34) + "http://www.w3.org/1999/xhtml" + Chr(34) + " xml:lang=" + Chr(34) + "en" + Chr(34) + ">" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "            <head>" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "                <meta http-equiv=" + Chr(34) + "Content-Type" + Chr(34) + " content=" + Chr(34) + "text/html; charset=UTF-8" + Chr(34) + "/>" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "                <meta name=" + Chr(34) + "calibre:cover" + Chr(34) + " content=" + Chr(34) + "true" + Chr(34) + "/>" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "                <title>Cover</title>" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "                <style type=" + Chr(34) + "text/css" + Chr(34) + " title=" + Chr(34) + "override_css" + Chr(34) + ">" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "                    @page {padding: 0pt; margin:0pt}" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "                    body { text-align: center; padding:0pt; margin: 0pt; }" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "                    div { padding:0pt; margin: 0pt; }" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "                </style>" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "            </head>" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "            <body>" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "                <div>" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "                    <img src=" + Chr(34) + "cover.jpg" + Chr(34) + " alt=" + Chr(34) + "cover" + Chr(34) + " style=" + Chr(34) + "height: 100%" + Chr(34) + "/>" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "                </div>" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "            </body>" + Chr(10)
                RichTextBox1.Text = RichTextBox1.Text + "        </html>"
                RichTextBox1.SaveFile(opfdirectory + "\titlepage.xhtml", RichTextBoxStreamType.PlainText)

                'make changes to opf file
                RichTextBox1.LoadFile(opffile, RichTextBoxStreamType.PlainText)

                'add item to metadata
                metadatafile = RichTextBox1.Text
                startpos = InStr(metadatafile, "</dc:title>")
                If startpos <> 0 Then
                    insertpos = InStr(startpos + 1, metadatafile, "<")
                    If insertpos <> 0 Then
                        newlineandspace = Mid(metadatafile, startpos + 11, insertpos - startpos - 11)
                        insertion = newlineandspace + "<meta name=" + Chr(34) + "cover" + Chr(34) + " content=" + Chr(34) + "cover" + Chr(34) + "/>" + newlineandspace
                        metadatafile = Mid(metadatafile, 1, startpos + 10) + insertion + Mid(metadatafile, insertpos, Len(metadatafile) - insertpos + 1)
                        RichTextBox1.Text = metadatafile
                    End If
                End If

                'add items to manifest
                metadatafile = RichTextBox1.Text
                startpos = InStr(metadatafile, "<manifest>")
                If startpos <> 0 Then
                    insertpos = InStr(startpos + 1, metadatafile, "<")
                    If insertpos <> 0 Then
                        newlineandspace = Mid(metadatafile, startpos + 10, insertpos - startpos - 10)
                        insertion = newlineandspace + "<item href=" + Chr(34) + "cover.jpg" + Chr(34) + " id=" + Chr(34) + "cover" + Chr(34) + " media-type=" + Chr(34) + "image/jpeg" + Chr(34) + "/>" + newlineandspace
                        insertion = insertion + "<item href=" + Chr(34) + "titlepage.xhtml" + Chr(34) + " id=" + Chr(34) + "titlepage" + Chr(34) + " media-type=" + Chr(34) + "application/xhtml+xml" + Chr(34) + "/>" + newlineandspace
                        metadatafile = Mid(metadatafile, 1, startpos + 9) + insertion + Mid(metadatafile, insertpos, Len(metadatafile) - insertpos + 1)
                        RichTextBox1.Text = metadatafile
                    End If
                End If

                'add item to spine
                metadatafile = RichTextBox1.Text
                startpos = InStr(metadatafile, "<spine")
                If startpos <> 0 Then
                    insertpos = InStr(startpos + 1, metadatafile, "<")
                    If insertpos <> 0 Then
                        startpos = insertpos
                        While (Mid(metadatafile, startpos, 1) <> Chr(10))
                            startpos = startpos - 1
                        End While
                        newlineandspace = Mid(metadatafile, startpos, insertpos - startpos)
                        insertion = "<itemref idref=" + Chr(34) + "titlepage" + Chr(34) + "/>"
                        metadatafile = Mid(metadatafile, 1, startpos - 1) + newlineandspace + insertion + newlineandspace + Mid(metadatafile, insertpos, Len(metadatafile) - insertpos + 1)
                        RichTextBox1.Text = metadatafile
                    End If
                End If

                'add reference to guide
                metadatafile = RichTextBox1.Text
                startpos = InStr(metadatafile, "<guide>")
                If startpos <> 0 Then
                    insertpos = InStr(startpos + 1, metadatafile, "<")
                    If insertpos <> 0 Then
                        newlineandspace = Mid(metadatafile, startpos + 7, insertpos - startpos - 7)
                        insertion = newlineandspace + "<reference href=" + Chr(34) + "titlepage.xhtml" + Chr(34) + " type=" + Chr(34) + "cover" + Chr(34) + " title=" + Chr(34) + "Cover" + Chr(34) + "/>" + newlineandspace
                        metadatafile = Mid(metadatafile, 1, startpos + 6) + insertion + Mid(metadatafile, insertpos, Len(metadatafile) - insertpos + 1)
                        RichTextBox1.Text = metadatafile
                    End If
                Else
                    'look for <guide/> and delete it
                    metadatafile = metadatafile.Replace("<guide/>", "")

                    'now create <guide>
                    startpos = InStr(metadatafile, "</package>")
                    If startpos <> 0 Then
                        insertion = "<guide>" + Chr(10) + "    <reference href=" + Chr(34) + "titlepage.xhtml" + Chr(34) + " type=" + Chr(34) + "cover" + Chr(34) + " title=" + Chr(34) + "Cover" + Chr(34) + "/>" + Chr(10) + "</guide>" + Chr(10)
                        metadatafile = Mid(metadatafile, 1, startpos - 1) + insertion + Mid(metadatafile, startpos, Len(metadatafile) - startpos + 1)
                        RichTextBox1.Text = metadatafile
                    End If
                End If

                'save opf file
                RichTextBox1.SaveFile(opffile, RichTextBoxStreamType.PlainText)
            End If

            'save image to file
            pic.Save(coverimagefile)

            'update interface
            PictureBox1.ImageLocation = coverimagefile
            PictureBox1.Load()
            ChangeImageToolStripMenuItem.Enabled = True
            AddImageToolStripMenuItem.Enabled = False
            projectchanged = True
            Button3.Enabled = True
            Me.Text = "*" + IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
        End If
    End Sub

    Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
        If CheckBox1.Checked = True Then CheckBox4.Checked = False
    End Sub

    Private Sub CheckBox4_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox4.CheckedChanged
        If CheckBox4.Checked = True Then CheckBox1.Checked = False
    End Sub
    Private Sub SaveEpub()
        Dim metadatafile, optionaltext As String
        Dim startpos, endpos, lenheader As Integer

        Dim fi As New FileInfo(OpenFileDialog1.FileName)
        If FileInUse(fi.FullName) Then
            MsgBox("ERROR: File in use!  Cannot save changes.", MsgBoxStyle.Critical, "EPubMetadataEditor")
            Exit Sub
        End If

        'Rewrite .opf file (just the metadata section)
        RichTextBox1.LoadFile(opffile, RichTextBoxStreamType.PlainText)
        metadatafile = RichTextBox1.Text

        'Output title
        startpos = InStr(metadatafile, "<dc:title")
        If startpos <> 0 Then
            endpos = InStr(metadatafile, "</dc:title>")
            lenheader = Len("<dc:title")

            'If optional attributes
            If TextBox16.Text <> "" Then
                optionaltext = " opf:file-as=" + Chr(34) + TextBox16.Text + Chr(34) + ">"
            Else
                optionaltext = ">"
            End If
            metadatafile = Mid(metadatafile, 1, startpos + lenheader - 1) + optionaltext + TextBox1.Text + Mid(metadatafile, endpos)
        End If

        'Output first creator
        startpos = InStr(metadatafile, "<dc:creator")
        If startpos <> 0 Then
            endpos = InStr(metadatafile, "</dc:creator>")
            lenheader = Len("<dc:creator")

            'If optional attributes
            If TextBox12.Text <> "" Then
                optionaltext = ""
                If ((ComboBox1.SelectedIndex = 0) Or (ComboBox1.SelectedIndex = -1)) Then optionaltext = " opf:role=" + Chr(34) + "aut" + Chr(34)
                If ComboBox1.SelectedIndex = 1 Then optionaltext = " opf:role=" + Chr(34) + "edt" + Chr(34)
                If ComboBox1.SelectedIndex = 2 Then optionaltext = " opf:role=" + Chr(34) + "ill" + Chr(34)
                If ComboBox1.SelectedIndex = 3 Then optionaltext = " opf:role=" + Chr(34) + "trl" + Chr(34)
                optionaltext = optionaltext + " opf:file-as=" + Chr(34) + TextBox12.Text + Chr(34) + ">"
            Else
                optionaltext = ">"
            End If
            metadatafile = Mid(metadatafile, 1, startpos + lenheader - 1) + optionaltext + TextBox2.Text + Mid(metadatafile, endpos)

            'Output second creator?
            endpos = InStr(metadatafile, "</dc:creator>") 'find end of first creator
            startpos = InStr(endpos, metadatafile, "<dc:creator") 'look for another one
            If ((TextBox3.Text <> "") Or (startpos <> 0)) Then
                'Get optional attributes
                If TextBox13.Text <> "" Then
                    optionaltext = ""
                    If ((ComboBox2.SelectedIndex = 0) Or (ComboBox2.SelectedIndex = -1)) Then optionaltext = " opf:role=" + Chr(34) + "aut" + Chr(34)
                    If ComboBox2.SelectedIndex = 1 Then optionaltext = " opf:role=" + Chr(34) + "edt" + Chr(34)
                    If ComboBox2.SelectedIndex = 2 Then optionaltext = " opf:role=" + Chr(34) + "ill" + Chr(34)
                    If ComboBox2.SelectedIndex = 3 Then optionaltext = " opf:role=" + Chr(34) + "trl" + Chr(34)
                    optionaltext = optionaltext + " opf:file-as=" + Chr(34) + TextBox13.Text + Chr(34) + ">"
                Else
                    optionaltext = ">"
                End If
                If startpos <> 0 Then
                    endpos = InStr(startpos, metadatafile, "</dc:creator>")
                    lenheader = Len("<dc:creator")
                    metadatafile = Mid(metadatafile, 1, startpos + lenheader - 1) + optionaltext + TextBox3.Text + Mid(metadatafile, endpos)
                Else
                    'Original file did not have second creator
                    metadatafile = Mid(metadatafile, 1, endpos + 13) + Chr(13) + Chr(10) + Chr(9) + "<dc:creator" + optionaltext + TextBox3.Text + "</dc:creator>" + Chr(13) + Chr(10) + Mid(metadatafile, endpos + 14)
                End If
            End If
        End If

        'Output (Calibre) series and series index
        startpos = InStr(metadatafile, "<meta name=" & Chr(34) & "calibre:series" & Chr(34))
        If ((TextBox15.Text <> "") Or (startpos <> 0)) Then
            If startpos <> 0 Then
                endpos = InStr(startpos, metadatafile, "/>")
                lenheader = Len("<meta name=" & Chr(34) & "calibre:series" & Chr(34))
                metadatafile = Mid(metadatafile, 1, startpos + lenheader - 1) + " content=" + Chr(34) + TextBox15.Text + Chr(34) + Mid(metadatafile, endpos)
            Else
                endpos = InStr(metadatafile, "</dc:title>")
                metadatafile = Mid(metadatafile, 1, endpos + 11) + Chr(13) + Chr(10) + Chr(9) + "<meta name=" & Chr(34) & "calibre:series" & Chr(34) & " content=" + Chr(34) + TextBox15.Text + Chr(34) + "/>" + Chr(13) + Chr(10) + Mid(metadatafile, endpos + 12)
            End If
        End If
        startpos = InStr(metadatafile, "<meta name=" & Chr(34) & "calibre:series_index" & Chr(34))
        If ((TextBox14.Text <> "") Or (startpos <> 0)) Then
            If startpos <> 0 Then
                endpos = InStr(startpos, metadatafile, "/>")
                lenheader = Len("<meta name=" & Chr(34) & "calibre:series_index" & Chr(34))
                metadatafile = Mid(metadatafile, 1, startpos + lenheader - 1) + " content=" + Chr(34) + TextBox14.Text + Chr(34) + Mid(metadatafile, endpos)
            Else
                endpos = InStr(metadatafile, "</dc:title>")
                metadatafile = Mid(metadatafile, 1, endpos + 11) + Chr(13) + Chr(10) + Chr(9) + "<meta name=" & Chr(34) & "calibre:series_index" & Chr(34) & " content=" + Chr(34) + TextBox14.Text + Chr(34) + "/>" + Chr(13) + Chr(10) + Mid(metadatafile, endpos + 12)
            End If
        End If

        'Output description
        startpos = InStr(metadatafile, "<dc:description>")
        If ((TextBox4.Text <> "") Or (startpos <> 0)) Then
            If startpos <> 0 Then
                endpos = InStr(metadatafile, "</dc:description>")
                lenheader = Len("<dc:description>")
                metadatafile = Mid(metadatafile, 1, startpos + lenheader - 1) + TextBox4.Text + Mid(metadatafile, endpos)
            Else
                endpos = InStr(metadatafile, "</dc:title>")
                metadatafile = Mid(metadatafile, 1, endpos + 11) + Chr(13) + Chr(10) + Chr(9) + "<dc:description>" + TextBox4.Text + "</dc:description>" + Chr(13) + Chr(10) + Mid(metadatafile, endpos + 12)
            End If
        End If

        'Output publisher
        startpos = InStr(metadatafile, "<dc:publisher>")
        If ((TextBox5.Text <> "") Or (startpos <> 0)) Then
            If startpos <> 0 Then
                endpos = InStr(metadatafile, "</dc:publisher>")
                lenheader = Len("<dc:publisher>")
                metadatafile = Mid(metadatafile, 1, startpos + lenheader - 1) + TextBox5.Text + Mid(metadatafile, endpos)
            Else
                endpos = InStr(metadatafile, "</dc:title>")
                metadatafile = Mid(metadatafile, 1, endpos + 11) + Chr(13) + Chr(10) + Chr(9) + "<dc:publisher>" + TextBox5.Text + "</dc:publisher>" + Chr(13) + Chr(10) + Mid(metadatafile, endpos + 12)
            End If
        End If

        'Output date
        startpos = InStr(metadatafile, "<dc:date")
        If ((TextBox6.Text <> "") Or (startpos <> 0)) Then
            If startpos <> 0 Then
                endpos = InStr(metadatafile, "</dc:date>")
                lenheader = Len("<dc:date")
                metadatafile = Mid(metadatafile, 1, startpos + lenheader - 1) + " opf:event=" + Chr(34) + "original-publication" + Chr(34) + ">" + TextBox6.Text + Mid(metadatafile, endpos)
            Else
                endpos = InStr(metadatafile, "</dc:title>")
                metadatafile = Mid(metadatafile, 1, endpos + 11) + Chr(13) + Chr(10) + Chr(9) + "<dc:date" + " opf:event=" + Chr(34) + "original-publication" + Chr(34) + ">" + TextBox6.Text + "</dc:date>" + Chr(13) + Chr(10) + Mid(metadatafile, endpos + 12)
            End If
        End If

        'Output type
        startpos = InStr(metadatafile, "<dc:type>")
        If ((TextBox7.Text <> "") Or (startpos <> 0)) Then
            If startpos <> 0 Then
                endpos = InStr(metadatafile, "</dc:type>")
                lenheader = Len("<dc:type>")
                metadatafile = Mid(metadatafile, 1, startpos + lenheader - 1) + TextBox7.Text + Mid(metadatafile, endpos)
            Else
                endpos = InStr(metadatafile, "</dc:title>")
                metadatafile = Mid(metadatafile, 1, endpos + 11) + Chr(13) + Chr(10) + Chr(9) + "<dc:type>" + TextBox7.Text + "</dc:type>" + Chr(13) + Chr(10) + Mid(metadatafile, endpos + 12)
            End If
        End If

        'Output format
        startpos = InStr(metadatafile, "<dc:format>")
        If ((TextBox8.Text <> "") Or (startpos <> 0)) Then
            If startpos <> 0 Then
                endpos = InStr(metadatafile, "</dc:format>")
                lenheader = Len("<dc:format>")
                metadatafile = Mid(metadatafile, 1, startpos + lenheader - 1) + TextBox8.Text + Mid(metadatafile, endpos)
            Else
                endpos = InStr(metadatafile, "</dc:title>")
                metadatafile = Mid(metadatafile, 1, endpos + 11) + Chr(13) + Chr(10) + Chr(9) + "<dc:format>" + TextBox8.Text + "</dc:format>" + Chr(13) + Chr(10) + Mid(metadatafile, endpos + 12)
            End If
        End If

        'Output identifier
        startpos = InStr(metadatafile, "<dc:identifier>")
        If ((TextBox9.Text <> "") Or (startpos <> 0)) Then
            If startpos <> 0 Then
                endpos = InStr(metadatafile, "</dc:identifier>")
                lenheader = Len("<dc:identifier>")
                metadatafile = Mid(metadatafile, 1, startpos + lenheader - 1) + TextBox9.Text + Mid(metadatafile, endpos)
            Else
                endpos = InStr(metadatafile, "</dc:title>")
                metadatafile = Mid(metadatafile, 1, endpos + 11) + Chr(13) + Chr(10) + Chr(9) + "<dc:identifier>" + TextBox9.Text + "</dc:identifier>" + Chr(13) + Chr(10) + Mid(metadatafile, endpos + 12)
            End If
        End If

        'Output source
        startpos = InStr(metadatafile, "<dc:source>")
        If ((TextBox10.Text <> "") Or (startpos <> 0)) Then
            If startpos <> 0 Then
                endpos = InStr(metadatafile, "</dc:source>")
                lenheader = Len("<dc:source>")
                metadatafile = Mid(metadatafile, 1, startpos + lenheader - 1) + TextBox10.Text + Mid(metadatafile, endpos)
            Else
                endpos = InStr(metadatafile, "</dc:title>")
                metadatafile = Mid(metadatafile, 1, endpos + 11) + Chr(13) + Chr(10) + Chr(9) + "<dc:source>" + TextBox10.Text + "</dc:source>" + Chr(13) + Chr(10) + Mid(metadatafile, endpos + 12)
            End If
        End If

        'Output language
        startpos = InStr(metadatafile, "<dc:language>")
        If ((TextBox11.Text <> "") Or (startpos <> 0)) Then
            If startpos <> 0 Then
                endpos = InStr(metadatafile, "</dc:language>")
                lenheader = Len("<dc:language>")
                metadatafile = Mid(metadatafile, 1, startpos + lenheader - 1) + TextBox11.Text + Mid(metadatafile, endpos)
            Else
                endpos = InStr(metadatafile, "</dc:title>")
                metadatafile = Mid(metadatafile, 1, endpos + 11) + Chr(13) + Chr(10) + Chr(9) + "<dc:language>" + TextBox11.Text + "</dc:language>" + Chr(13) + Chr(10) + Mid(metadatafile, endpos + 12)
            End If
        End If

        RichTextBox1.Text = metadatafile
        RichTextBox1.SaveFile(opffile, RichTextBoxStreamType.PlainText)

        'Zip temp directory (after deleting original file)
        fi.Delete()

        Using zip As ZipFile = New ZipFile
            zip.AddDirectory(ebookdirectory)
            zip.Save(OpenFileDialog1.FileName)
        End Using

        'Update interface
        Me.Text = IO.Path.GetFileName(OpenFileDialog1.FileName) + " - EPub Metadata Editor"
        Button3.Enabled = False
        projectchanged = False
    End Sub
End Class
